策略模式非常的简单,对于 Java 来说,就是一个接口多种实现,使用不同的实现就是更换策略。

1 策略模式案例

先定义好策略接口

1
2
3
public interface Strategy {
   public int doOperation(int num1, int num2);
}

然后对策略接口做不同的实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class OperationAdd implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 + num2;
   }
}
public class OperationSubstract implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 - num2;
   }
}
public class OperationMultiply implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 * num2;
   }
}

接下来对策略类做一层包装,这层包装感觉不做也没什么关系,实际使用的时候我们使用 Spring 注入的时候,更换成不同的 Bean 就行了。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Context {
   private Strategy strategy;
 
   public Context(Strategy strategy){
      this.strategy = strategy;
   }
 
   public int executeStrategy(int num1, int num2){
      return strategy.doOperation(num1, num2);
   }
}

接下来是调用看效果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class StrategyPatternDemo {
   public static void main(String[] args) {
      Context context = new Context(new OperationAdd());    
      System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
 
      context = new Context(new OperationSubstract());      
      System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
 
      context = new Context(new OperationMultiply());    
      System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
   }
}

输出结果

1
2
3
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50

参考资料

  1. 菜鸟教程: 策略模式