使用策略模式彻底消除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);

    }
}

测试运行结果:



相关推荐
ghostwritten1 天前
macOS安装配置Unbound DNS完整指南
macos·策略模式·dns
超龄超能程序猿1 天前
Vue3 + Electron 技术栈下 MAC 地址获取的方法、准确性优化与应对策略
macos·electron·策略模式
万粉变现经纪人2 天前
如何解决pip安装报错ModuleNotFoundError: No module named ‘dash’问题
python·scrapy·pycharm·flask·pip·策略模式·dash
IT小白架构师之路3 天前
常用设计模式系列(十六)—策略模式
设计模式·bash·策略模式
zy小狮子5 天前
【设计模式系列】策略模式vs模板模式
设计模式·策略模式
愿你天黑有灯下雨有伞5 天前
枚举策略模式实战:优雅消除支付场景的if-else
java·开发语言·策略模式
JosieBook5 天前
【IDEA】idea怎么修改注册的用户名称?
java·intellij-idea·策略模式
蝸牛ちゃん6 天前
设计模式(二十二)行为型:策略模式详解
设计模式·系统架构·软考高级·策略模式
喝可乐的希饭a8 天前
Spring 策略模式实现
java·spring·策略模式
未既10 天前
java设计模式 -【策略模式】
java·设计模式·策略模式