设计模式-策略模式,介绍策略模式,及代码实现。
简介
策略模式,它定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的用户。
优点
- 策略模式以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。
- 策略模式的Strategy类层次为Context定义了一系列的可重用的算法行为,继承有助于提取出这些算法中的公用功能。
- 策略模式简化了单元测试,每个算法都有自己的类,可以通过自己的接口单独测试。
- 策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间应有不同的业务规则,就可以考虑使用策略模式处理这个变化。
角色
- 策略类:定义所有支持的算法的公共接口
- 具体策略类:封装了具体的算法行为,继承或实现策略类
- 上下文:用具体策略类配置,维护一个策略类对象的引用
代码实现
策略接口及实现子类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
public interface Strategy { public void algorithmInterface(); }
class ConcreteStrategyA implements Strategy {
@Override public void algorithmInterface() { System.out.println("策略A的具体算法实现"); }
}
class ConcreteStrategyB implements Strategy {
@Override public void algorithmInterface() { System.out.println("策略B的具体算法实现"); }
}
class ConcreteStrategyC implements Strategy {
@Override public void algorithmInterface() { System.out.println("策略C的具体算法实现"); }
}
|
上下文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
public class Context {
Strategy strategy;
public Context(Strategy strategy) { this.strategy = strategy; }
public void contextInterface() { strategy.algorithmInterface(); }
}
|
客户端调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public class StrategyClient { public static void main(String[] args) { Context context;
context = new Context(new ConcreteStrategyA()); context.contextInterface();
context = new Context(new ConcreteStrategyB()); context.contextInterface();
context = new Context(new ConcreteStrategyC()); context.contextInterface();
} }
|