继承Java通过设计避免实例
考虑下面的课堂设计:
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()实现
# 1 楼答案
这里有一个简单的解决方案选项,您可以使用它,将
Generics
用于类型safe&Polymorphism
在每个子类中执行操作行为下面是向方法传递有效/无效参数的示例:
# 2 楼答案
在OO语言中实现这一点的正确方法是使用一种称为“双重分派”的模式(Googlable,但wikipedia的页面并不好)
“append”方法就是一个很好的例子: