考慮下面的類設計:爪哇避免的instanceof通過設計
public class SuperType { };
public class SubType1 extends SuperType { };
public class SubType2 extends SuperType { };
public class SubType3 extends SuperType { };
public class Tuple {
SuperType t1;
SuperType t2;
public Tuple(SuperType t1, SuperType t2) {
this.t1 = t1;
this.t2 = t2;
}
public void DoSomething1() {
if((t1 instanceof SubType1) && (t2 instanceof SubType3))
switch(t1, t2);
else if((t1 instanceof SubType2) && (t2 instanceof SubType1))
t1.DoSomething();
else if(...) {
t1.DoSomething();
t2.DoSomething();
}
else if(...)
// ...
}
public void DoSomething2() {
// basically the same
}
}
由於作用依賴於兩種類型的我不能由該方法移動到亞型避免instanceof運算符。有沒有一種方法可以改進我的設計,這樣我就可以避免使用instanceof?
我知道這裏有很多類似的問題,但我想避免使用訪問者,因爲我有大約20個DoSomething() - 將導致9 * 20實現visit()的方法。
取決於//做一些動作實際上做了什麼? – Rehman
這太寬泛了。我們不知道「做某些行動」會發生什麼,但更重要的是,我們不知道您要實現什麼目標。避免使用'instanceof'的典型方法是正確使用接口。 – Tunaki
爲什麼你不使用多態?做你的行動 – Husam