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 !

如果有更好的方法或有问题的地方,麻烦大家留言,我也学习一下!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值