Originally the idea is to use a structure of element classes, each of which has an accept method
that takes a visitor object as an argument. The visitor is an interface that has different visit
methods for each element class. The accept()
method of an element class calls back
the visitEnter()
and visitLeave
methods for its class.
Separate concrete visitor classes can then be written that perform some particular operations. One of these visit methods of a concrete visitor can be thought of as methods not of a single class, but rather methods of a pair of classes: the concrete visitor and the particular element class. Thus the visitor pattern simulates double dispatch in a conventional single-dispatch object-oriented language such as Java.
The visitor pattern also specifies how iteration occurs over the object structure. In the
simplest version, where each algorithm needs to iterate in the same way, the
accept()
method for a container element, in addition to calling back the
visitEnter()
method of the visitor, also passes the visitor object to the
accept()
method of all its constituent child elements. At the end the method
visitLeave
is called.
Here we also decouple the transverse mechanism from the elements to gain control over the iteration over the object structure.
See Wikepedia article.