在Java中避免使用instanceof具有一系列“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映射到一個IntegerStuff的實例,將BigDecimal.class映射到一個BigDecimalStuff的實例等等。但是今天我想要一些更簡單的東西。)我想要像這樣簡單的東西:public static handle(Integer num) { ... }public static handle(BigDecimal num) { ... }但是Java不會那樣工作。我想在格式化時使用靜態方法。我正在格式化的東西是復合的,其中Thing1可以包含一個數組Thing2s和Thing2可以包含一個Thing1s數組。當我實現這樣的格式化程序時,我遇到了問題: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”似乎更具可讀性和可維護性。有什么簡單但不臭嗎?注釋已添加5/10/2010:事實證明,將來可能會添加新的子類,而我現有的代碼必須優雅地處理它們。在這種情況下,類上的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}
3 回答

12345678_0001
TA貢獻1802條經驗 獲得超5個贊
正如評論中所強調的那樣,訪客模式將是一個不錯的選擇。但是如果沒有對目標/接受者/被訪者的直接控制,則無法實現該模式。這里是訪問者模式可能仍然可以在這里使用的一種方式,即使你沒有使用包裝器直接控制子類(以Integer為例):
public class IntegerWrapper { private Integer integer; public IntegerWrapper(Integer anInteger){ integer = anInteger; } //Access the integer directly such as public Integer getInteger() { return integer; } //or method passthrough... public int intValue() { return integer.intValue(); } //then implement your visitor: public void accept(NumericVisitor visitor) { visitor.visit(this); }}
當然,包裝最終類可能被認為是它自己的氣味,但也許它很適合你的子類。就我個人而言,我認為instanceof
這里的味道不是很糟糕,特別是如果只限于一種方法,我會很樂意使用它(可能超過我自己的建議)。正如你所說,它具有可讀性,類型安全性和可維護性。一如既往,保持簡單。
添加回答
舉報
0/150
提交
取消