从而造成一系列的算法,并让这些算法能够相互替换。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(); } }