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

    }
}

测试运行结果:



相关推荐
「QT(C++)开发工程师」2 天前
C++ 策略模式
开发语言·c++·策略模式
佑白雪乐2 天前
<Linux基础12集>1-11集大复习Review
linux·运维·策略模式
临水逸4 天前
OpenClaw WebUI 的外网访问配置
人工智能·策略模式
她说..4 天前
策略模式+工厂模式实现订单校验功能
java·spring boot·java-ee·简单工厂模式·策略模式
短剑重铸之日4 天前
《设计模式》第五篇:策略模式
java·后端·设计模式·策略模式
帅得不敢出门4 天前
Android定位RK编译的system.img比MTK大350M的原因
android·framework·策略模式
琹箐4 天前
设计模式——策略模式
设计模式·策略模式
她说..5 天前
策略模式+工厂模式实现审批流(面试问答版)
java·后端·spring·面试·springboot·策略模式·javaee
进击的小头6 天前
设计模式组合应用:嵌入式通信协议栈
c语言·设计模式·策略模式
Wyy_9527*6 天前
行为型设计模式——策略模式
设计模式·策略模式