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

    }
}

测试运行结果:



相关推荐
一个在高校打杂的1 天前
honeypot之opencanary(轻量化蜜罐)
linux·网络安全·网络攻击模型·安全威胁分析·策略模式
蜡笔小马2 天前
13.C++设计模式-策略模式
c++·设计模式·策略模式
杜子不疼.3 天前
【C++ AI 大模型接入 SDK】 - LLMProvider 抽象基类与策略模式
开发语言·c++·策略模式
代码对我眨眼睛4 天前
Mac 如何单独修改鼠标滚动方向,而不影响触控板
macos·计算机外设·策略模式
jiushiaifenxiang4 天前
Parallels Desktop for Mac 26.3.2 (57398)中文版新功能介绍
macos·策略模式
雪碧聊技术5 天前
什么是策略模式?一文详解
策略模式
johnny2337 天前
终端文件管理器:Yazi、nnn、Superfile、lf、Ranger、walk
策略模式
AI砖家7 天前
DeepSeek TUI 保姆级安装配置全指南 -Windows||macOS双平台全覆盖
服务器·前端·人工智能·windows·macos·ai编程·策略模式
有梦想的小何7 天前
Cursor AI 编程实战(篇三):Domain、Infrastructure 与策略模式
java·ai编程·策略模式
多加点辣也没关系8 天前
设计模式-策略模式
java·设计模式·策略模式