转载

设计模式之策略模式

设计模式之策略模式

什么是策略模式?

策略模式定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。

UML

下面用具体代码来解释该模式

首先定义所有支持的算法的公共接口,Strategy接口

 package strategy;  public interface Strategy {     void algorithmInterface(); } 

其次定义封装了具体算法或行为接口实现类ABC

 package strategy;  public class ConcreteStrategyA implements Strategy {      @Override     public void algorithmInterface() {         // TODO Auto-generated method stub         System.out.println("A");     }  } 
 package strategy;  public class ConcreteStrategyB implements Strategy {      @Override     public void algorithmInterface() {         // TODO Auto-generated method stub         System.out.println("B");     }  } 
 package strategy;  public class ConcreteStrategyC implements Strategy {      @Override     public void algorithmInterface() {         // TODO Auto-generated method stub         System.out.println("C");     }  } 

接着定义一个Context上下文,用一个具体的ConcreteStrategy来配置,维护一个对Strategy对象的引用

 package strategy;  public class Context {     Strategy strategy;     public Context(Strategy strategy) {         // TODO Auto-generated constructor stub         this.strategy=strategy;     }     public void contextInterface() {         strategy.algorithmInterface();     } } 

最后就是定义Test测试类了

 package strategy;  public class Test {     public static void main(String[] args) {         Context contextA=new Context(new ConcreteStrategyA());         contextA.contextInterface();         Context contextB=new Context(new ConcreteStrategyB());         contextB.contextInterface();         Context contextC=new Context(new ConcreteStrategyC());         contextC.contextInterface();              } } 

大功告成了么?

是不是觉得怪怪的?

此时程序又变成了很早之前的套路,也就是在客户端去判断用什么算法。那么有什么方法将判断转移出去呢?

下面将其与简单工厂模式进行结合

改造Context类

 package strategy;  public class ContextUpdate {     Strategy strategy;          public ContextUpdate(String type) {         // TODO Auto-generated constructor stub         switch (type) {         case "A":             strategy =new ConcreteStrategyA();             break;         case "B":             strategy =new ConcreteStrategyB();             break;         default:             strategy =new ConcreteStrategyC();             break;         }     }          public void concreteStrategy() {         strategy.algorithmInterface();     } } 

此时判断便从客户端转移出去了

初学《设计模式》

正文到此结束
Loading...