参考博文:https://www.cnblogs.com/lewis0077/p/5133812.html 侵权删除
2019-06-17 11:39:49
策略模式(Strategy)
什么是设计模式:定义了一系列的算法(多种实现子类),并将每一个算法封装(通过父类策略引用访问具体子类的算法)起来,使每个算法可以相互替代,使算法本身和使用算法的客户端分割开来,相互独立。(客户端和具体算法均依赖抽象的策略)
优点:符合设计模式中的开闭原则(在不修改既有代码的基础上扩展功能)。
适用性:一个需求有多种不同算法的场合。(不固定的 if-else 场合一般是策略模式的用武之地)
基本代码如下:
1 //接口或抽象类,策略接口 2 public interface Strategy{ 3 //定义抽象的算法方法 4 public void algorithMethod(); 5 }
1 //具体的策略1实现 2 public class ConcreteStrategy1 implements Strategy{ 3 public void algorithmMethod(){ 4 //........具体策略1的方法体 5 } 6 }
//具体的策略2实现 public class ConcreteStrategy2 implements Strategy{ public void algorithmMethod(){ //........具体策略2的方法体 } }
1 public class StrategyContext{ 2 private Strategy strategy; //持有策略的引用 3 public StrategyContext( Strategy strategy){
4 this.strategy = strategy; 5 } 6 7 public void contextMethod(){ 8 otherMethod(); 9 strategy.algorithMethod(); 10 otherMethod(); 11 } 12 }
1 //外部客户端 2 public class Client{ 3 public static void main(String[] args) { 4 //具体测策略实现 5 IStrategy strategy = new ConcreteStrategy2(); //父类引用指向子类 6 //将具体的策略实现对象注入到策略上下文当中 7 StrategyContext ctx = new StrategyContext(strategy); 8 //调用上下文对象的方法来完成对具体策略实现的回调 9 ctx.contextMethod(); //调用时,会找到具体的策略 10 } 11 }
总结:
1 策略上下文依赖抽象策略,具体策略依赖抽象策略。(依赖抽象)
2 如需要扩展策略功能,在现有的基础上再设计一个策略的实现类,而不需要修改原有的代码。(开闭原则)
3 父类应用指向子类。(多态)