天天看點

Java 去除難看的if-else

這陣子項目要使用的業務不可避免的要使用很多if-else,我知道東西寫多了會很難看,是以想辦法,并查閱了一些資料。

[這裡是我查閱的資料,在它的基礎上對代碼進行修改](http://www.qingjingjie.com/blogs/8)

閑話不說,直接上代碼

**注意:必須使用jdk8或以上版本**

1.首先建立一個animal類,隻有一個成員
           
public class Animal {

    private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}
           

2.添加一個主類(Demo.java),這裡編寫核心代碼

public class Demo {

    private static Map<String, Function<Animal, Boolean>> maps = new HashMap<String, Function<Animal, Boolean>>();

    static {
        //這裡用到landa表達式,新特性。 其中 Cat,Dog 可以看成 if-else 中的條件
        maps.put("Cat", bean -> RunCase1(bean));
        maps.put("Dog", bean -> RunCase2(bean));
    }

    public static void main(String[] args) {

        Animal animal = new Animal();

        animal.setType("Dog");

        Iterator iterator = maps.entrySet().iterator();

        while (iterator.hasNext()) {

            Entry entry = (Entry) iterator.next();

            //本來有倆個if,現在變成一個,而且永遠隻有一個
            if (entry.getKey().toString().equals(animal.getType())) {
                Function<Animal, Boolean> f = (Function<Animal, Boolean>) entry.getValue();

                f.apply(animal);
            }

        }

    }

    private static Boolean RunCase2(Animal animal) {

        System.out.println("The " + animal.getType() + " say:" + "I am  dog !");
        return true;
    }

    private static Boolean RunCase1(Animal animal) {

        System.out.println("The " + animal.getType() + " say:" + "I am  cat !");
        return false;
    }

}
           

以上程式運作結果為:

The Dog say:I am dog !

如果有更好的方法或有問題的地方,麻煩大家留言,我也學習一下!