java基础

干掉多层 if else

2018-09-12  本文已影响0人  java面试收割机

当代码业务逻辑有多层 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);
    }
}

上一篇下一篇

猜你喜欢

热点阅读