设计模式-策略模式

结构图:

实现:

1 abstract public class Strategy {
2     public void algrithmInterface()
3     {    
4     }
5 }
 1 public class StrategyA extends Strategy{
 2 
 3     @Override
 4     public void algrithmInterface() {
 5         super.algrithmInterface();
 6         System.out.println("算法A的实现");
 7     }
 8     
 9 
10 }
 1 public class StrategyB extends Strategy{
 2 
 3     @Override
 4     public void algrithmInterface() {
 5         super.algrithmInterface();
 6         System.out.println("算法B的实现");
 7     }
 8     
 9 
10 }
 1 public class Context {
 2 
 3     private Strategy strategy;
 4 
 5     public Context(Strategy strategy) {
 6         super();
 7         this.strategy = strategy;
 8     }
 9     
10     public void contextInterface()
11     {
12         strategy.algrithmInterface();
13     }
14     
15     public void setStrategy(Strategy s)
16     {
17         this.strategy = s;
18     }
19 }
 1 public class Client {
 2     public static void main(String[] args)
 3     {
 4         Context context = new Context(new StrategyA());
 5         context.contextInterface();
 6         
 7         context.setStrategy(new StrategyB());
 8         context.contextInterface();
 9     }
10 }

应用常用:
该模式封装了一系列算法,让它们而已相互替换,而不会影响到客户端的变化。

原文地址:https://www.cnblogs.com/gatsbydhn/p/4998698.html