策略模式定义了一系列的算法,并将每个算法封装起来,并且使他们能够相互替换,让算法独立于使用它的客户而独立变化。java
1.在系统里面许多类,类之间区别仅在于方法行为,那么策略模式能够动态的从一个对象在许多行为中选择一种行为
2.一个系统须要动态地在几种算法中选择一种算法
抽象策略类测试
public interface Strategy(){ public void print(); }
具体策略类this
public class PrintA implements Strategy{ public void print(){ System.out.println("我是A"); } } public class PrintB implements Strategy{ public void print(){ System.out.println("我是B"); } }
环境角色code
public class Context{ private Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy; } public void contextInterface(){ strategy.print(); } }
测试对象
public static void main(String[] args){ Context context = new Context(new PrintA()); context.contextInterface(); Context context = new Context(new PrintB()); context.contextInterface(); }