一连串的“instanceof”操作被认为是一种“代码异味”。标准答案是“使用多态性”。在这种情况下,我该怎么做呢?
有许多基类的子类;它们中没有一个受到我的控制。类比的情况是Java类Integer、Double、BigDecimal等。
if (obj instanceof Integer) {NumberStuff.handle((Integer)obj);}
else if (obj instanceof BigDecimal) {BigDecimalStuff.handle((BigDecimal)obj);}
else if (obj instanceof Double) {DoubleStuff.handle((Double)obj);}
我对NumberStuff等具有控制权。
我不想使用很多行代码来完成只需要几行的工作。(有时我会创建一个HashMap,将Integer.class映射到一个IntegerStuff实例,BigDecimal.class映射到一个BigDecimalStuff实例等等。但是今天我想要更简单的方法。)
我想要像这样简单:
public static handle(Integer num) { ... }
public static handle(BigDecimal num) { ... }
但 Java 并不是这样工作的。
我想在格式化时使用静态方法。 我要格式化的对象是复合类型,其中 Thing1 可以包含一个 Thing2 数组,而 Thing2 可以包含一个 Thing1 数组。 当我像这样实现我的格式化程序时,出现了问题:
class Thing1Formatter {
private static Thing2Formatter thing2Formatter = new Thing2Formatter();
public format(Thing thing) {
thing2Formatter.format(thing.innerThing2);
}
}
class Thing2Formatter {
private static Thing1Formatter thing1Formatter = new Thing1Formatter();
public format(Thing2 thing) {
thing1Formatter.format(thing.innerThing1);
}
}
是的,我知道使用HashMap和更多代码也可以解决这个问题。但相比之下,“instanceof”似乎更易于阅读和维护。有没有什么简单的方法而不会让人感到困扰?
注:已于2010年5月10日添加说明:
事实证明,未来可能会添加新的子类,我的现有代码必须优雅地处理它们。在这种情况下,Class上的HashMap将无法正常工作,因为找不到该类。一系列的if语句,从最具体的开始,以最普遍的结束,可能是最好的选择:
if (obj instanceof SubClass1) {
// Handle all the methods and properties of SubClass1
} else if (obj instanceof SubClass2) {
// Handle all the methods and properties of SubClass2
} else if (obj instanceof Interface3) {
// Unknown class but it implements Interface3
// so handle those methods and properties
} else if (obj instanceof Interface4) {
// likewise. May want to also handle case of
// object that implements both interfaces.
} else {
// New (unknown) subclass; do what I can with the base class
}