相关文章
【合集】Java设计模式
    
    
总结
其实就是合成复用 + 依赖倒转
策略模式
策略接口
| 1
2
3
 | public interface Strategy {
    void show();
}
 | 
 
具体策略
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
 | public static class StrategyA implements Strategy {
    public void show() {
        System.out.println("买一送一");
    }
}
public static class StrategyB implements Strategy {
    public void show() {
        System.out.println("满200元减50元");
    }
}
public static class StrategyC implements Strategy {
    public void show() {
        System.out.println("满1000元加一元换购任意200元以下商品");
    }
}
 | 
 
环境角色,连接上下文
| 1
2
3
4
5
6
7
8
9
 | @Setter
public static class SalesMan {
    private Strategy strategy;
    public SalesMan() {
    }
    public void salesManShow() {
        strategy.show();
    }
}
 | 
 
客户端调用
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
 | SalesMan salesMan = new SalesMan();
salesMan.setStrategy(new StrategyA());
salesMan.salesManShow(); // 买一送一
salesMan.setStrategy(new StrategyB());
salesMan.salesManShow(); // 满200元减50元
salesMan.setStrategy(new StrategyC());
salesMan.salesManShow(); // 满1000元加一元换购任意200元以下商品
 | 
 
应用
{@link Arrays#sort(Object[], Comparator)},Comparator就是抽象策略角色,它的实现就是具体策略类(最终调用它重写的compare方法)