java - 实现两个相似类的方法时是否可以避免重复代码?
问题描述
我有两个班级:Fish
和Plant
。它们不继承自任何类。
但是它们都有一个称为isAlive()
具有相同实现细节的方法。现在我有一个鱼列表和另一个狗列表,我需要删除死鱼和死狗。我希望我的方法具有相同的名称,但如果不向方法签名添加其他字段是不可能的。是否有可能我不需要编写与最后一段代码相同的额外代码块?
下面是代码。对于 class Model
,Fish
andPlant
是两个数据成员,它们是 ArrayListFish
和Plant
对象。
有什么方法可以只编写一个名为 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;
}
}
解决方案
如果不想使用继承,那么可以使用通用方法:
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);
}
}
推荐阅读
- reactjs - Twilio flex UI 获取工作人员属性并仅向管理员显示 sideNav 按钮
- intellij-idea - IntelliJ 迁移到 Junit5 - 空的重构窗口
- javascript - 如何在 node.js 应用程序中使用 ethers.js contract.on() 监听来自智能合约的事件?
- java - 在 SD 卡上打开视频时 net::ERR_ACCESS_DENIED
- javascript - 使用 JavaScript 的 multiplyOddByTwo 函数
- c++ - C ++将派生类的成员函数分配给指向基类函数的指针
- amazon-web-services - IAM 角色未显示在修改 IAM 角色页面的 aws 控制台中
- vba - 宏在 excel 2010 中无法按预期工作
- c# - 我可以将 Azure.Core 命名空间用于非天蓝色项目吗?
- python - 从 2 个字符串列表中获取一个列表