Re: Visitor pattern vs if-ladder
Tom Anderson wrote:
On Fri, 24 Apr 2009, Giovanni Azua wrote:
Having to write an accept method each time specially in larger
hierarchies
that statically maps to the right overloading visit counterpart is indeed
error-prone e.g. you just might forget to call visit.
That would be a remarkable thing to forget, given that that call is the
only thing accept has to do. This is accept:
public void accept(Visitor v) {
v.visit(this);
}
So to forget to call visit, you'd have to write this:
public void accept(Visitor v) {
}
Which would be quite a surprising thing to write!
I just want to clarify something here. Given that a concrete Element
which already implements the visitor pattern, there's no need for
sub-classes of that concrete element to re-implement the visitor
pattern. At least, none that I see.
interface Element {
void accept( Visitor v );
}
class ConcreteElementA implements Element {
public void accept( Visitor v )
{
v.VisitA( this );
}
}
interface Visitor {
void VisitA( ConcreteElementA e );
void VisitB( ConcreteElementB e );
}
There's no need for any children of ConcreteElementA to reimplement the
visitor pattern. In fact, they can't, since there's no method for them
to call in this Visitor interface.
Now if you add a method :
interface Visitor {
void VisitA( ConcreteElementA e );
void VisitB( ConcreteElementB e );
void VisitSubSubA( ConcreteElementAAA e );}
}
Then you have something to do for grandchildren of ConcreteElementA, but
only if your design actually requires that those classes are treated
differently than their ancestors.
Did I miss something?