策略模式:在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。
也就是说,定义一个接口,实现该接口表示为多种策略,定义一个Context对象,Context对象会跟着策略对象的改变而改变。
1 public interface Strategy { 2 public int doOperation(int num1, int num2); 3 } 4 5 public class OperationAdd implements Strategy{ 6 @Override 7 public int doOperation(int num1, int num2) { 8 return num1 + num2; 9 } 10 } 11 12 public class OperationSubstract implements Strategy{ 13 @Override 14 public int doOperation(int num1, int num2) { 15 return num1 - num2; 16 } 17 } 18 19 public class OperationMultiply implements Strategy{ 20 @Override 21 public int doOperation(int num1, int num2) { 22 return num1 * num2; 23 } 24 } 25 26 public class Context { 27 private Strategy strategy; 28 29 public Context(Strategy strategy){ 30 this.strategy = strategy; 31 } 32 33 public int executeStrategy(int num1, int num2){ 34 return strategy.doOperation(num1, num2); 35 } 36 } 37 38 public class StrategyPatternDemo { 39 public static void main(String[] args) { 40 Context context = new Context(new OperationAdd()); 41 System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); 42 43 context = new Context(new OperationSubstract()); 44 System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); 45 46 context = new Context(new OperationMultiply()); 47 System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); 48 } 49 }
原文:https://www.cnblogs.com/seedss/p/12783801.html