使用多态替代if/else

if/else的做法:

package com.huowolf.polymorphic;

public class Demo {

    public static void main(String[] args) {
        System.out.println(FruitsUtil.isNeedKnife(new Apple()));
        System.out.println(FruitsUtil.isNeedKnife(new Banana()));
        System.out.println(FruitsUtil.isNeedKnife(new Watermelon()));
    }
}


class FruitsUtil {
    public static boolean isNeedKnife(Object obj){
        if(obj instanceof Apple){
            return false;
        }else if(obj instanceof Banana){
            return false;
        }else if(obj instanceof Watermelon){
            return true;
        }
        return false;
    }
}

class Apple{}

class Banana{}

class Watermelon{}

使用多态的做法:

package com.huowolf.polymorphic.improve;

public class Demo2 {

    public static void main(String[] args) {
        System.out.println(FruitsUtil.needKnife(new Apple()));
        System.out.println(FruitsUtil.needKnife(new Banana()));
        System.out.println(FruitsUtil.needKnife(new Watermelon()));
    }
}

class FruitsUtil {
    public static boolean needKnife(Fruits fruits){
        return fruits.isNeedKnife();
    }
}

abstract class Fruits{
    public abstract boolean isNeedKnife();
}

class Apple extends Fruits{

    @Override
    public boolean isNeedKnife() {
        return false;
    }
}

class Banana extends Fruits{

    @Override
    public boolean isNeedKnife() {
        return false;
    }
}

class Watermelon extends Fruits{

    @Override
    public boolean isNeedKnife() {
        return true;
    }
}

 

你可能感兴趣的:(Java基础,java,多态,if/else,策略模式)