策略模式:定義了不同的算法,分別分裝起來,讓他們可以互相替換,即使算法變化了,也不會影響到使用算法的用戶
首先定義一個抽象算法類,有兩個類繼承了這個抽象類,重寫了AlgorithmInterface()方法
public abstract class Strategy { public abstract void AlgorithmInterface(); } public class AlgorithmA extends Strategy { @Override public void AlgorithmInterface() { System.out.println("實現算法A"); } } public class AlgorithmB extends Strategy { @Override public void AlgorithmInterface() { System.out.println("實現算法B"); } }
用一個context類來維護對抽象算法類Strategy對象的引用(重點)
public class Context { Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy; } public void ContrxtInterface(){ strategy.AlgorithmInterface(); } }
測試類1
public class Test1 { public static void main(String[] args) { Context context = null; context = new Context(new AlgorithmA()); context.ContrxtInterface(); context = new Context(new AlgorithmB()); context.ContrxtInterface(); } }
但是從上面測試類1的代碼我們發現是在客戶端判斷是用什么算法,現在我們想把這個判斷交由其他類處理,於是就有了下面的策略模式與簡單工廠結合的方法。
public class Context2 { Strategy strategy = null; public Context2(String type){ switch (type){ case "A": strategy = new AlgorithmA(); break; case "B": strategy = new AlgorithmB(); break; } } public void ContrxtInterface(){ strategy.AlgorithmInterface(); } }
測試類2
public class Text2 { public static void main(String[] args) { Context2 context2A = new Context2("A"); context2A.ContrxtInterface(); Context2 context2B = new Context2("B"); context2B.ContrxtInterface(); } }
結論:策略模式定義一系列算法,他們完成的都是同一件事,只是實現方法不同,比如超市收銀時,會員打折,非會員不打折,實現的都是收錢,實現方法(打折/非打折)不同。
優點:1.上下文和具體策略是松耦合關系。因此上下文只知道它要使用某一個實現Strategy接口類的實例,但不需要知道具體是哪一個類。
2.策略模式滿足“開-閉原則”。當增加新的具體策略時,不需要修改上下文類的代碼,上下文就可以引用新的具體策略的實例。