第0章:簡介
策略模式定義:定義一系列算法,把它們一個個封裝起來,並且使它們可互相替換。本模式使得算法可獨立於使用它的客戶而變化
策略模式本質:分離算法,選擇實現
參考:http://chjavach.iteye.com/blog/696977,研磨設計模式(書籍),大話設計模式(書籍)
模式圖:
待補充
第1章:實踐
(1)策略接口(Strategy.java)
package com.mcc.core.designPattern.behavior.strategy; /** * 策略接口 * * 策略模式的定義:定義一系列算法,把它們一個個封裝起來,並且使它們可互相替換。本模式使得算法可獨立於使用它的客戶而變化 * 策略模式的本質:分離算法,選擇實現 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-16 下午7:03 */ public interface Strategy { public void someMethod(); } |
(2)策略A(StrategyImplA.java)
package com.mcc.core.designPattern.behavior.strategy; /** * 策略A * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-16 下午7:05 */ public class StrategyImplA implements Strategy { @Override public void someMethod() { System.out.println("執行策略A操作"); } } |
(3)策略B(StrategyImplB.java)
package com.mcc.core.designPattern.behavior.strategy; /** * 策略B * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-16 下午7:05 */ public class StrategyImplB implements Strategy { @Override public void someMethod() { System.out.println("執行策略B操作"); } } |
(4)策略C(StrategyImplC.java)
package com.mcc.core.designPattern.behavior.strategy; /** * 策略C * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-16 下午7:05 */ public class StrategyImplC implements Strategy { @Override public void someMethod() { System.out.println("執行策略C操作"); } } |
(5)上下文對象(Context.java)
package com.mcc.core.designPattern.behavior.strategy; /** * 上下文對象,通常持有具體的策略對象 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-16 下午7:06 */ public class Context { //持有具體的策略對象 private Strategy strategy; /** * 構造器,傳入具體的策略對象 * @param strategy */ public Context(Strategy strategy){ this.strategy = strategy; } /** * 上下文對外接口,可以有其它參數和其它操作 */ public void execute(){ //轉調具體策略對象的方法 strategy.someMethod(); } } |
(6)客戶端測試(Client.java)
package com.mcc.core.designPattern.behavior.strategy; /** * 客戶端測試 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-16 下午7:11 */ public class Client { public static void main(String args[]){ //創建策略對象 Strategy strategyA = new StrategyImplA(); Strategy strategyB = new StrategyImplB(); Strategy strategyC = new StrategyImplC(); //創建上下文並執行策略A Context contextA = new Context(strategyA); contextA.execute(); //創建上下文並執行策略B Context contextB = new Context(strategyB); contextB.execute(); //創建上下文並執行策略C Context contextC = new Context(strategyC); contextC.execute(); } } |