設計模式之策略模式
設計模式之策略模式
什么是策略模式?
策略模式定義了算法家族,分別封裝起來,讓它們之間可以相互替換,此模式讓算法的變化,不會影響到使用算法的客戶。
UML
下面用具體代碼來解釋該模式
首先定義所有支持的算法的公共接口,Strategy接口
package strategy;public interface Strategy { void algorithmInterface(); } </pre>
其次定義封裝了具體算法或行為接口實現類ABC
package strategy;public class ConcreteStrategyA implements Strategy {
@Override public void algorithmInterface() { // TODO Auto-generated method stub System.out.println("A"); }
} </pre>
package strategy;public class ConcreteStrategyB implements Strategy {
@Override public void algorithmInterface() { // TODO Auto-generated method stub System.out.println("B"); }
} </pre>
package strategy;public class ConcreteStrategyC implements Strategy {
@Override public void algorithmInterface() { // TODO Auto-generated method stub System.out.println("C"); }
} </pre>
接著定義一個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(); } } </pre>
最后就是定義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();
}
} </pre>
大功告成了么?
是不是覺得怪怪的?
此時程序又變成了很早之前的套路,也就是在客戶端去判斷用什么算法。那么有什么方法將判斷轉移出去呢?
下面將其與簡單工廠模式進行結合
改造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(); }
} </pre>
此時判斷便從客戶端轉移出去了
初學《設計模式》
</div>來自: http://www.cnblogs.com/zhaoww/p/5090996.html
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!