策略模式Strategy
原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11400764.html
1. 定义
定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
2.结构图
- Strategy:策略接口,用来约束一系列具体的策略算法。Context使用这个接口来调用具体的策略实现定义的算法。
- ConcreteStrategy:具体的策略实现,也就是具体的算法实现。
- Context:上下文,负责和具体的策略类交互。通常上下文会持有一个真正的策略实现,上下文还可以让具体的策略类来获取上下文的数据,甚至让具体的策略类来回调上下文的方法。
3. 本质
策略模式的本质:分离算法,选择实现。
4.Code Demo
Strategy.java
1 package org.fool.dp.strategy; 2 3 public interface Strategy { 4 int calculate(int a, int b); 5 }
AddStrategy.java
1 package org.fool.dp.strategy; 2 3 public class AddStrategy implements Strategy { 4 @Override 5 public int calculate(int a, int b) { 6 return a + b; 7 } 8 }
SubtractStrategy.java
1 package org.fool.dp.strategy; 2 3 public class SubtractStrategy implements Strategy { 4 @Override 5 public int calculate(int a, int b) { 6 return a - b; 7 } 8 }
MultiplyStrategy.java
1 package org.fool.dp.strategy; 2 3 public class MultiplyStrategy implements Strategy { 4 @Override 5 public int calculate(int a, int b) { 6 return a * b; 7 } 8 }
DivideStrategy.java
1 package org.fool.dp.strategy; 2 3 public class DivideStrategy implements Strategy { 4 @Override 5 public int calculate(int a, int b) { 6 return a / b; 7 } 8 }
Context.java
1 package org.fool.dp.strategy; 2 3 public class Context { 4 private Strategy strategy; 5 6 public Context(Strategy strategy) { 7 this.strategy = strategy; 8 } 9 10 public int calculate(int a, int b) { 11 return strategy.calculate(a, b); 12 } 13 }
Client.java
1 package org.fool.dp.strategy; 2 3 public class Client { 4 public static void main(String[] args) { 5 Strategy addStrategy = new AddStrategy(); 6 Context context = new Context(addStrategy); 7 System.out.println(context.calculate(1, 2)); 8 9 Strategy subtractStrategy = new SubtractStrategy(); 10 context = new Context(subtractStrategy); 11 System.out.println(context.calculate(1, 2)); 12 13 Strategy multiplyStrategy = new MultiplyStrategy(); 14 context = new Context(multiplyStrategy); 15 System.out.println(context.calculate(1, 2)); 16 17 Strategy devideStrategy = new DivideStrategy(); 18 context = new Context(devideStrategy); 19 System.out.println(context.calculate(1, 2)); 20 } 21 }
强者自救 圣者渡人