策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.)
实例
算法接口:Strategy.java
package strategy; public interface Strategy { public void AlgorithmInterface(); }
具体算法A实现:ConcreteStrategyA.java
package strategy; public class ConcreteStrategyA implements Strategy { @Override public void AlgorithmInterface() { // TODO Auto-generated method stub System.out.println("具体算法A实现"); } }
具体算法B实现:ConcreteStrategyB.java
package strategy; public class ConcreteStrategyB implements Strategy { @Override public void AlgorithmInterface() { // TODO Auto-generated method stub System.out.println("具体算法B实现"); } }
上下文类,维护一个对Strategy对象的引用:Context.java
package strategy; public class Context { public Context(Strategy strategy) { //初始化时,传入具体的策略对象 this.strategy = strategy; } public void contextInterface() { strategy.AlgorithmInterface(); } private Strategy strategy; }
Main函数:Main.java
package strategy; public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Context context; //算法A context = new Context(new ConcreteStrategyA()); context.contextInterface(); //算法B context = new Context(new ConcreteStrategyB()); context.contextInterface(); } }