從而造成一系列的算法,並讓這些算法能夠相互替換。java
的維護性和擴展性。算法
優勢: 1,避免多重條件語句。this
2,更好的擴展性(增長新的實現類)。
spa
缺點: 1,客戶端必須知道全部的策略類。code
2,增長了對象數目。對象
來個簡單的例子:接口
/** * 1.對策略對象定義一個公共接口。 * 2.編寫策略類,該類實現了上面的公共接口。 * 3.在使用策略對象的類中保存一個對策略對象的引用。 * 4.在使用策略對象的類中,實現對策略對象的set和get方法。 */ class StrategyExample { public static void main(String[] args) { Context context; context.setStrategy(new FirstStrategy()); context.execute(); context.setStrategy(new SecondStrategy()); context.execute(); context.setStrategy(new ThirdStrategy()); context.execute(); } } //定義策略接口 interface Strategy { void execute(); } //定義策略實現類 class FirstStrategy implements Strategy { public void execute() { System.out.println("Called FirstStrategy.execute()"); } } //定義策略實現類 class SecondStrategy implements Strategy { public void execute() { System.out.println("Called SecondStrategy.execute()"); } } //定義策略實現類 class ThirdStrategy implements Strategy { public void execute() { System.out.println("Called ThirdStrategy.execute()"); } } //定義使用策略的上下文 class Context { Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void setStrategy(Strategy strategy) { this.strategy = strategy; } public Strategy getStrategy() { return this.strategy; } public void execute() { this.strategy.execute(); } }