14_策略模式

2021-01-17  本文已影响0人  真是个点子王

结构

实例

// Strategy.java
public interface Strategy {
    public void show();
}

// StrategyA.java
public class StrategyA implements Strategy{
    @Override
    public void show() {
        System.out.println("买一送一");
    }
}

// SalesMan.java
public class SalesMan {

    // 聚合策略类对象
    private Strategy strategy;

    public SalesMan(Strategy strategy) {
        this.strategy = strategy;
    }

    // 由促销员展示促销活动给普通用户
    public void salesManShow(){
        strategy.show();
    }
}

// Client.java
public class Client {
    public static void main(String[] args) {
        SalesMan salesMan = new SalesMan(new StrategyA());
        salesMan.salesManShow();
        SalesMan salesMan1 = new SalesMan(new Strategy() {
            @Override
            public void show() {
                System.out.println("明天不要钱");
            }
        });
        salesMan1.salesManShow();
    }
}

/*
Output:
买一送一
明天不要钱
*/

分析

上一篇下一篇

猜你喜欢

热点阅读