策略模式定义了算法家族, 分别封装起来, 让他们之间可以相互替换, 此模式让算法的变化影响到使用的客户。
代码
1public interface Strategy {
2 void Algorithm();
3}
1public class StrategyA implements Strategy {
2 @Override
3 public void Algorithm() {
4 System.out.println("使用了StrategyA的算法");
5 }
6}
1public class StrategyB implements Strategy{
2 @Override
3 public void Algorithm() {
4 System.out.println("使用了StrategyB的算法");
5 }
6}
1public class Context{
2 Strategy strategy;
3
4 public Context(Strategy strategy) {
5 this.strategy = strategy;
6 }
7
8 public void contextOperate(){
9 this.strategy.Algorithm();
10 }
11}
1public class Main {
2 public static void main(String[] args) {
3 Context context;
4 context = new Context(new StrategyA());
5 context.contextOperate();
6
7 context = new Context(new StrategyB());
8 context.contextOperate();
9 }
10}
策略模式其实就是一个计划, 通过执行这个计划, 我们在既定的输入下给出特定的输出。
策略通常可以表达为一组方案(也可以理解为一组算法), 这些方案之间可以相互替换.