通常如果一个问题有多个解决方案或者稍有区别的操作时,最简单的方式就是利用if-else or switch-case方式来解决,对于简单的解决方案这样做无疑是比较简单、方便、快捷的,但是如果解决方案中包括大量的处理逻辑需要封装,或者处理方式变动较大的时候则就显得混乱、复杂,而策略模式则很好的解决了这样的问题,它将各种方案分离开来,让操作者根据具体的需求来动态的选择不同的策略方案。 这里以简单的计算操作(+、-、*、/)作为示例:
/** * 减法的具体实现策略 */ public class SubStrategy implements Strategy { @Override public double calc(double paramA, double paramB) { System.out.println("Execute SubStrategy"); return paramA - paramB; } }
MultiStrategy.java
1 2 3 4 5 6 7 8 9 10 11
/** * 乘法的具体实现策略 */ public class MultiStrategy implements Strategy { @Override public double calc(double paramA, double paramB) { System.out.println("Execute MultiStrategy"); return paramA * paramB; } }
DivStrategy.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/** * 除法的具体实现策略 */ public class DivStrategy implements Strategy { @Override public double calc(double paramA, double paramB) { System.out.println("Execute DivStrategy"); if (paramB == 0) { throw new IllegalArgumentException("Cannot divide into 0"); } return paramA / paramB; } }
Calc.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/** * 进行计算操作的上下文环境 */ public class Calc {
private Strategy mStrategy;
public void setStrategy(Strategy strategy) { this.mStrategy = strategy; }
public double calc(double paramA, double paramB) { if (mStrategy == null) { throw new IllegalStateException("You haven't set the strategy for computing."); } return mStrategy.calc(paramA, paramB); } }
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public class MyClass {
public double calc(Strategy strategy, double paramA, double paramB) { Calc calc = new Calc(); calc.setStrategy(strategy); return calc.calc(paramA, paramB); }