定义
策略模式(Strategy),它定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法得变化,不会影响到使用算法得用户。
代码实现如下:
1 public abstract class Strategy { 2 //算法方法 3 public abstract void algorithInterface(); 4 }
1 public class ConcreteStrategyA extends Strategy { 2 3 @Override 4 public void algorithInterface() { 5 System.out.println("A实现"); 6 7 } 8 9 }
1 public class ConcreteStrategyB extends Strategy { 2 3 @Override 4 public void algorithInterface() { 5 System.out.println("B实现"); 6 7 } 8 9 }
1 public class ConcreteStrategyC extends Strategy { 2 3 @Override 4 public void algorithInterface() { 5 System.out.println("C实现"); 6 } 7 8 }
1 public class Context { 2 Strategy strategy; 3 4 public Context(Strategy strategy) { 5 this.strategy = strategy; 6 } 7 8 public void contextInterface(){ 9 strategy.algorithInterface(); 10 } 11 }
1 public class TestStrategy { 2 public static void main(String[] args) { 3 Context context; 4 context = new Context(new ConcreteStrategyA()); 5 context.contextInterface(); 6 context = new Context(new ConcreteStrategyB()); 7 context.contextInterface(); 8 context = new Context(new ConcreteStrategyC()); 9 context.contextInterface(); 10 } 11 }
A实现
B实现
C实现