Consider the following class design:
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
}
}
Since the action is dependent on two types I cant avoid the instanceof operator by moving the method to the subtypes. Is there a way I can improve my design so I can avoid using instanceof?
I know there are a lot of similar questions here, but I'd like to avoid the use of a visitor, because I have around twenty DoSomething()-Methods which would result in 9*20 implementations of visit().
// Do some actionactually does ?// Do some actiondoes but more importantly, we don't know what goal you are trying to achieve. The typical way to avoidinstanceofis to have a proper use of interface.