策略模式实战运用(优化业务逻辑中的 if else 代码块)

目录

前言

UML

plantuml

类图

代码

操作枚举类

测试类


前言

业务开发时,不同的业务代码值下需要执行不同的业务逻辑,最直接的做法就是堆砌 if else 来判断后再执行相应的业务逻辑。这样子做功能是可以实现,只不过就是开发一时爽,维护火葬场。

若业务的选择分支多且业务逻辑复杂的情况下,那么此处代码会变得十分臃肿,违背单一职责原则。

若业务需求有变动的话,修改则有可能影响其它业务逻辑,违背开闭原则。

这种业务场景可以使用策略模式来实现,将不同的业务逻辑拆分到不同的策略类中,根据不同的业务代码拿到不同的策略,来执行不同的业务逻辑。

大量使用策略模式会带来类膨胀问题,在小项目中这么搞,就显得很过度设计,这里使用枚举类的方式来平替接口+实现类的方式。

UML

plantuml

@startuml
'https://plantuml.com/class-diagram

interface Strategy {
    + method() : void
}

class StrategyA {
    + method() : void
}

class StrategyB {
    + method() : void
}

class Context {
    + method(Strategy) : void
}

Strategy <|.. StrategyA
Strategy <|.. StrategyB

Context ..> Strategy

@enduml

类图

代码

操作枚举类

public enum Operation {
    GT(1, "大于") {
        public boolean execute(int value1, int value2) {
            return value1 > value2;
        }
    },
    EQ(2, "等于") {
        public boolean execute(int value1, int value2) {
            return value1 == value2;
        }
    },
    LT(3, "小于") {
        public boolean execute(int value1, int value2) {
            return value1 < value2;
        }
    };

    private final Integer value;
    private final String desc;
    private static final Map<Integer, Operation> map = Arrays.stream(values())
            .collect(toMap(Operation::getValue, e -> e));

    private Operation(Integer value, String desc) {
        this.value = value;
        this.desc = desc;
    }

    public Integer getValue() {
        return this.value;
    }

    public String getDesc() {
        return this.desc;
    }

    public boolean execute(int value1, int value2) {
        throw new RuntimeException("未知操作类型");
    }

    public static Operation getEnum(Integer value) {
        return (Operation)map.get(value);
    }

}

测试类

public class Test {

    public static void main(String[] args) {
        Operation operation;
        operation = Operation.getEnum(1);
        System.out.println(operation.getDesc() + " " + operation.execute(1, 2));

        operation = Operation.getEnum(2);
        System.out.println(operation.getDesc() + " " + operation.execute(1, 2));

        operation = Operation.getEnum(3);
        System.out.println(operation.getDesc() + " " + operation.execute(1, 2));
    }
}

  • 56
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值