欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用枚举消除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);

 

 

相关标签: 百宝箱