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

    }
}

测试运行结果:



相关推荐
头发还在的女程序员9 天前
【免费下载】企业能源管理系统
小程序·策略模式·能源管理
前端 贾公子9 天前
React 和 Vue 都离不开的表单验证库 async-validator 之策略模式的应用 (上)
vue.js·react.js·策略模式
小米49610 天前
Js设计模式---策略模式
设计模式·策略模式
geovindu10 天前
python: Strategy Pattern
python·设计模式·策略模式
Hello.Reader13 天前
Flink 任务失败恢复机制Restart Strategy 和 Failover Strategy 怎么配才“又稳又不炸”
大数据·flink·策略模式
武帝为此15 天前
【Linux strace命令介绍】
linux·运维·策略模式
带娃的IT创业者16 天前
解密OpenClaw系列10-OpenClawSparkle框架集成
软件工程·agent·策略模式·自动更新·ai智能体·智能体开发·openclaw
茶本无香17 天前
【无标题】
java·设计模式·策略模式
驴儿响叮当201019 天前
设计模式之策略模式
设计模式·策略模式
kong790692820 天前
设计模式-策略模式
设计模式·策略模式·行为设计模式