考虑下面的类设计:爪哇避免的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