美文网首页java基础
干掉多层 if else

干掉多层 if else

作者: java面试收割机 | 来源:发表于2018-09-12 15:55 被阅读0次

当代码业务逻辑有多层 if else 时,不仅代码效率就会降低,而且也会影响代码美观,所以有没有方法可以解决这种多层 if 呢,答案肯定是有
1、使用享元模式+lamda
原代码:

if(key){            

}else if(key1){

}

优化后:

public class StreamTest {

    public static void main(String[] args) {

        Product pro = new Product();
        pro.setId(1);
        Map<String,ProductService> map = new HashMap<>();
        map.put("key", (param)->{param.setCreateDate(new Date());return param;});
        map.put("key1", (param)->{param.setId(19);;return param;});
        System.out.println(JSONObject.toJSONString(map.get("key1").excute(pro)));

    }
    
    public interface ProductService{
        Product excute(Product pro);
    }
}

原代码:

public class StreamTest {

    public static void main(String[] args) {

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
        
        String today = null;
        switch(week){
            case 0:
                today = "周日";
                break;
            case 1 : 
                today = "周一"; 
                break;
            case 2 :
                today = "周二"; 
                break;
            case 3 :
                today = "周三"; 
                break;
            case 4 :
                today = "周四";
                break;
            case 5 :
                today = "周五"; 
                break;
            default:
                today = "周六";   
        }
        System.out.println(today);
    }
}

使用享元模式后:

public class StreamTest {

    public static void main(String[] args) {

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
        
        String [] weekday = new String[]{"周日","周一","周二","周三",
                "周四","周五","周六"};
        String today = weekday [ week ];
        System.out.println(today);
    }
}

相关文章

  • 干掉多层 if else

    当代码业务逻辑有多层 if else 时,不仅代码效率就会降低,而且也会影响代码美观,所以有没有方法可以解决这种多...

  • java 干掉if else

  • 逆向思考,优化/重构你的代码逻辑

    阅读陈皓博客代码优化, 写了此篇文章,多层if else值得深思,至少现在我已经在优化多层if情况了. 函数中多层...

  • 如何 “干掉” if...else

    前言 if...else 是所有高级编程语言都有的必备功能。但现实中的代码往往存在着过多的 if...else。虽...

  • 策略模式,Web 后端业务干掉 if else ?别闹...

    最近的这段时间,关于推荐使用策略模式干掉 if else 的言论很多。后来结合了一下自己实际项目上的经验,想干掉 ...

  • 别再用if-else了,用注解去代替他吧

    策略模式 经常在网上看到一些名为“别再if-else走天下了”,“教你干掉if-else”等之类的文章,大部分都会...

  • 策略模式

    一、为什么要用策略模式 经常在网上看到一些名为“别再if-else走天下了”,“教你干掉if-else”等之类的文...

  • 巧用 Spring @Autowired 干掉 else if

    代码可能这样 @Autowired用法 @Autowired 官方文档 利用这种方式的自动注入,可以将同一个接口的...

  • 策略模式

    业务复杂=if else?刚来的大神竟然用策略+工厂彻底干掉了他们! https://juejin.im/post...

  • 设计模式之状态模式

    在开发过程中,我们经常会遇到很多if-else的判断,有的会有很多层,当然也不是说所有的涉及到if-else判断的...

网友评论

    本文标题:干掉多层 if else

    本文链接:https://www.haomeiwen.com/subject/vtamgftx.html