用枚举消除if-else
程序员文章站
2024-01-20 16:55:58
...
目录
今天不知道哪位大神保佑,让我突然想起了曾经写过的一段多达十多个的if...else,被自己恶心到了,今天仔细想了想,梳理了一个自己觉得很优雅的化解此局的方法
定义操作
/**
* @author bemav
*/
@Service
public class CalculateService {
public Integer add(Integer a,Integer b){
return a+b;
}
public Integer subtract(Integer a,Integer b){
return a-b;
}
public Integer multiply(Integer a,Integer b){
return a*b;
}
public Integer divide(Integer a,Integer b){
return a/b;
}
}
定义枚举
并且将枚举对应的操作也赋到枚举上
@Getter
public enum OperationEnum {
ADD("CREATE", SpringApplicationContextHolder.getBean(CalculateService.class)::add),
SUBSTRACT("DELETE",SpringApplicationContextHolder.getBean(CalculateService.class)::subtract),
MULTIPLY("DELETE",SpringApplicationContextHolder.getBean(CalculateService.class)::multiply),
DIVIDE("UPDATE",SpringApplicationContextHolder.getBean(CalculateService.class)::divide),
TEST("UPDTESTATE",(a,b)->a-b);
private String operation;
private BiFunction<Integer,Integer,Integer> biFunction;
OperationEnum(String operation,BiFunction<Integer,Integer,Integer> biFunction){
this.operation=operation;
this.biFunction=biFunction;
}
public static OperationEnum getInstance(String operation){
for (OperationEnum operationEnum: OperationEnum.values()){
if (operationEnum.getOperation().equals(operation)){
return operationEnum;
}
}
return null;
}
}
使用方式
OperationEnum.getInstance("ADD").getBiFunction().apply(3,5);
上一篇: 日常CV积累