JAVA简化IF ELSE(map+函数式接口)

在开发过程中容易遇见很多个if的情况,当多个if调去方法,感觉代码很乱,突然想到通过map+函数式接口来完成优化。就有了下面的例子。
注意:在实际开发中还是以代码可读性为主,尽量不要设计的太复杂。

public class IF1 {
    public static void main(String[] args) {
        // 常规调用
        new IF1().if1("code1");

        System.out.println("=== 分割线 ===");

        // 利用map+Runnable函数式接口调用
        new IF1().sucessIf("code2");
    }

    /**
     * 优雅调用
     */
    public void sucessIf(String action){
        // 方法构建
        Map<String, Runnable> actionMap = new HashMap<>();
        actionMap.put("code1", this::doAction1);
        actionMap.put("code2", this::doAction2);
        actionMap.put("code3", this::doAction3);
        actionMap.put("code4", this::doAction4);
        actionMap.put("code5", this::doAction5);

        // 调用方法
        actionMap.get(action).run();

    }



    /**
     * 正常IF—ELSE调用
     */
    public void if1(String action){
        if ("code1".equals(action)) {
            doAction1();
        } else if ("code2".equals(action)) {
            doAction2();
        } else if ("code3".equals(action)) {
            doAction3();
        } else if ("code4".equals(action)) {
            doAction4();
        } else if ("code5".equals(action)) {
            doAction5();
        }
    }

    public void doAction1() {
        System.out.println("doAction1");
    }

    public void doAction2() {
        System.out.println("doAction2");
    }

    public void doAction3() {
        System.out.println("doAction3");
    }

    public void doAction4() {
        System.out.println("doAction4");
    }

    public void doAction5() {
        System.out.println("doAction5");
    }
}
  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值