Here is an excellent reference for the Visitor pattern, in which they mention the following:
When the accept() method is called in the program, its implementation
is chosen based on both:
- The dynamic type of the element.
- The static type of the visitor.
When the associated visit() method is called, its implementation is
chosen based on both:
- The dynamic type of the visitor.
- The static type of the element as known from within the implementation of the accept() method, which is the same as the
dynamic type of the element. (As a bonus, if the visitor can't handle
an argument of the given element's type, then the compiler will catch
the error.)
Consequently, the implementation of the visit() method is chosen based
on both:
- The dynamic type of the element.
- The dynamic type of the visitor.
Then they go on to mention the following:
This effectively implements double dispatch...
In this way, a single algorithm can be written for traversing a graph of
elements, and many different kinds of operations can be performed
during that traversal by supplying different kinds of visitors to
interact with the elements based on the dynamic types of both the
elements and the visitors.
Which can be seen in the Java car example:
class Car implements CarElement {
CarElement[] elements;
// ...
public void accept(CarElementVisitor visitor) {
for(CarElement elem : elements) {
elem.accept(visitor);
}
visitor.visit(this);
}
}
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:
- The original motivation for the pattern: which is to visit a complex structure of objects and perform operations on them without changing the class interfaces being visited.
- How the pattern is implemented: which is with the double dispatch as you mention.
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
- Allows you to add operations to a Composite structure without changing the structure itself
- Adding new operations is relatively easy
- The code for operations performed by the Visitor is centralized
CONs
- The Composite classes' encapsulation is broken when the Visitor is used.
- Because the traversal function is involved, changes to the Composite structure are more difficult