策略模式把所研究的对象的算法包装在不同的策略对象里,策略对象改变计算的结果也会发生改变。
    可以减少if else

    1. public interface Math {
    2. double calculate(double a, double b);
    3. }
    4. public class Add implements Math {
    5. @Override
    6. public double calculate(double a, double b) {
    7. return a + b;
    8. }
    9. }
    10. public class Multiply implements Math {
    11. @Override
    12. public double calculate(double a, double b) {
    13. return a * b;
    14. }
    15. }
    16. // 创建context
    17. public class StrategyContext {
    18. private Math math;
    19. public void setMath(Math math) {
    20. this.math = math;
    21. }
    22. public double getResult(double a, double b) {
    23. return math.calculate(a, b);
    24. }
    25. }
    1. public class Main {
    2. public static void main(String[] args) {
    3. StrategyContext strategyContext = new StrategyContext();
    4. strategyContext.setMath(new Add());
    5. System.out.println(strategyContext.getResult(1,2));
    6. strategyContext.setMath(new Multiply());
    7. System.out.println(strategyContext.getResult(1,2));
    8. }
    9. }