Why do we need both accept and visit functions in the visitor DP? if we take the typical example:
class Visitor {
visit(A a) { }
visit(B b) { }
}
interface Element {
accept(Visitor v);
}
class A implements Element {
accept(Visitor v) {
v.visit(this); // will call visit(A)
}
}
class B implements Element {
accept(Visitor v) {
v.visit(this); // will call visit(B)
}
}
To use the visitor DP, somewhere we have an instance v of Visitor, and an instance e of Element, and we do:
e.visit(v)
which simply calls
v.visit(e)
so why can’t we simply do the second call and bypass the mediator function? Since I think the GoF are not dumb, I guess I’m missing something. What is it?
Here is an excellent reference for the Visitor pattern, in which they mention the following:
Then they go on to mention the following:
Which can be seen in the Java car example:
So, to summarize, in your example, you wont get much benefit from the original DP implementation, but if the example is more complex, for example its a Composite with several internal implementations of Element (like the Java car example above), then it can apply the visitor behavior to some or all of its internal elements.
Based on the comments to your original question, there are 2 parts to this pattern:
I highly recommend the following design patterns book, as it really simplifies many of the concepts. The GoF book is sometimes too academic.
Head First Design Patterns
According to this book, here are the pros and cons to using the Visitor:
(In the context of the example used)
PROs
CONs