inheritance - Java avoiding instanceof by design -
consider 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() { // same } }
since action dependent on 2 types cant avoid instanceof operator moving method subtypes. there way can improve design can avoid using instanceof?
i know there lot of similar questions here, i'd avoid use of visitor, because have around twenty dosomething()-methods result in 9*20 implementations of visit().
the proper way in oo language using pattern called "double-dispatch" (googlable, wikipedia's page on not great).
an "append" method makes example:
class super { abstract void appendto(super target); abstract void append(sub1 source); abstract void append(sub2 source); } class sub1 { void appendto(super target) { target->append(this); //calls sub1 overload } void append(sub1 source) { ... sub1, source sub1 ... } void append(sub2 source) { ... sub1, source sub2 ... } } class sub2 { void appendto(super target) { target->append(this); //calls sub2 overload } void append(sub1 source) { ... sub2, source sub1 ... } void append(sub2 source) { ... sub2, source sub2 ... } }
Comments
Post a Comment