使用策略模式彻底消除if-else

文章目录

使用策略模式彻底消除if-else

如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现,这样会显得代码逻辑很臃肿,那么有没有方式去消除这种逻辑呢?答案当然是有,那就是使用策略模式

1. 场景描述

java 复制代码
接下来我们演示一下根据传入的不同参数执行不同的计算功能:

 - 如果传入的是PLUS,执行数据a+b计算;
 - 如果传入的是MINUS,执行数据a-b计算;
 - 如果传入的是MULTIPLY,执行数据a*b计算;
 - 否则执行数据a/b计算。

2. if-else方式

java 复制代码
public class StrategyDemo {
    public static void main(String[] args) {
        Integer result = count(3, 5, "MULTIPLY");
        System.out.println(result);
    }

    public static Integer count(Integer a, Integer b, String opt) {
        if ("PLUS".equals(opt)) {
            return a + b;
        } else if ("MINUS".equals(opt)){
            return a - b;
        } else if ("MULTIPLY".equals(opt)) {
            return a * b;
        } else {
            return a / b;
        }
    }
}

3. 策略模式

定义计算接口

java 复制代码
public interface ArithmeticOperation {

    /**
     * 计算
     *
     * @param a 待计算值
     * @param b 待计算值
     * @return 计算结果
     */
    int calculate(int a, int b);
}

定义枚举类并实现计算接口

java 复制代码
public enum ArithmeticEnum implements ArithmeticOperation{

    /**
     * 加
     */
    PLUS {
        @Override
        public int calculate(int a, int b) {
            return a + b;
        }
    },
    /**
     * 减
     */
    MINUS {
        @Override
        public int calculate(int a, int b) {
            return a - b;
        }
    },
    /**
     * 乘
     */
    MULTIPLY {
        @Override
        public int calculate(int a, int b) {
            return a * b;
        }
    },
    /**
     * 除
     */
    DIVIDE {
        @Override
        public int calculate(int a, int b) {
            return a / b;
        }
    };

}

使用

java 复制代码
public class StrategyDemo {


    public static void main(String[] args) {
        
        Integer result = count(3, 5, "MULTIPLY");

        System.out.println(result);

    }

    public static Integer count(Integer a, Integer b, String opt) {

        ArithmeticEnum arithmeticEnum = ArithmeticEnum.valueOf(opt);
        return arithmeticEnum.calculate(a, b);

    }
}

测试运行结果:



相关推荐
汤姆大聪明20 小时前
【软件设计模式】策略模式
设计模式·策略模式
xiaogg36782 天前
SpringBoot applicationContext.getBeansOfType获取某一接口所有实现类,应用于策略模式
java·spring boot·策略模式
Best_Liu~2 天前
策略模式 vs 适配器模式
java·spring boot·适配器模式·策略模式
Ronin-Lotus2 天前
上位机知识篇---命名规则
策略模式
南猿北者5 天前
Cmake学习笔记
笔记·学习·策略模式
哆啦code梦6 天前
趣谈设计模式之策略模式-比特咖啡给你一杯满满的情绪价值,让您在数字世界里”畅饮“
设计模式·策略模式
克拉克盖博8 天前
chapter03_Bean的实例化与策略模式
java·spring·策略模式
我命由我1234510 天前
软件开发 - 避免过多的 if-else 语句(使用策略模式、使用映射表、使用枚举、使用函数式编程)
java·开发语言·javascript·设计模式·java-ee·策略模式·js
饕餮争锋10 天前
设计模式笔记_行为型_策略模式
笔记·设计模式·策略模式
二进制coder10 天前
OpenBMC中C++策略模式架构、原理与应用
c++·架构·策略模式