首页 > 解决方案 > 实现两个相似类的方法时是否可以避免重复代码?

问题描述

我有两个班级:FishPlant。它们不继承自任何类。

但是它们都有一个称为isAlive()具有相同实现细节的方法。现在我有一个鱼列表和另一个狗列表,我需要删除死鱼和死狗。我希望我的方法具有相同的名称,但如果不向方法签名添加其他字段是不可能的。是否有可能我不需要编写与最后一段代码相同的额外代码块?

下面是代码。对于 class ModelFishandPlant是两个数据成员,它们是 ArrayListFishPlant对象。

有什么方法可以只编写一个名为 count 的方法,并且不需要在方法签名中添加其他字段或修改返回类型?

public class Fish{
    public boolean isAlive(){
        if(this.size > 0){
            return true;
        }
        return false;
    }
}
public class Plant{
    public boolean isAlive(){
        if(this.size > 0){
            return true;
        }
        return false;
    }
}

public class Model{
    private int countDeadFish() {
        int totalCount = 0;
        for(Fish aFish : this.fish) {
            if(aFish.isAlive() == false) {
                totalCount += 1;
            }
        }
        return totalCount;
    }

    private int countDeadPlants() {
        int totalCount = 0;
        for(Plant plant : this.plants) {
            if(plant.isAlive() == false) {
                totalCount += 1;
            }
        }
        return totalCount;
    }
}

标签: javaoverloading

解决方案


如果不想使用继承,那么可以使用通用方法:

public class AliveChecker {

    public static boolean isAlive(int size) {
        return size > 0;
    }

}

public class Plant{
    public boolean isAlive(){
        return AliveChecker.isAlive(this.size);
    }
}

public class Fish{
    public boolean isAlive(){
        return AliveChecker.isAlive(this.size);
    }
}

推荐阅读