我想从我的代码中删除许多 if/else 条件。我选择多态来代替它。我已经明白了方法。我正在复制我在互联网上找到的来源。
abstract class Bird {
// ...
abstract double getSpeed();
}
class European extends Bird {
double getSpeed() {
return getBaseSpeed();
}
}
class African extends Bird {
double getSpeed() {
return getBaseSpeed() - getLoadFactor() * numberOfCoconuts;
}
}
class NorwegianBlue extends Bird {
double getSpeed() {
return (isNailed) ? 0 : getBaseSpeed(voltage);
}
}
// Somewhere in client code
speed = bird.getSpeed();
我对上面的设计很满意。 但我的疑问是,如果bird对象的实例化依赖于另一个if/else条件。那么如何解决呢?我很困惑。请原谅我。这可能是非常微不足道的。 例如
if (LocalDateTime.now().getMonth().toString().equalsIgnoreCase("march")) {
Bird aBird = new European();
} else if (LocalDateTime.now().getMonth().toString().equalsIgnoreCase("August")) {
Bird aBird = new African();
}
speed = aBird.getSpeed();
请告诉我如何消除这个 if/else。
最佳答案
您必须使用 if/else,因为构造函数仅适用于已实现的类
你可以做得更好一点,像这样:
Bird aBird = null;
String month = LocalDateTime.now().getMonth().toString();
if ("march".equalsIgnoreCase(month)) {
aBird = new European();
} else if ("August".equalsIgnoreCase(month)) {
aBird = new African();
}
speed = aBird.getSpeed();
工厂的实现。
关于java - 使用 Java 中的多态性替换 If/Else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60939106/