目录
前言
业务开发时,不同的业务代码值下需要执行不同的业务逻辑,最直接的做法就是堆砌 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));
}
}