Visitor pattern
The visitor design pattern is a way of seperating an algorithm from an object structure.
The basic idea is that you have a set of element classes that form an object structure. Each of these element classes has an accept method that takes a Visitor object as an argument. The Visitor is an interface that has a different visit method for each element class. The accept method of an element class calls back the visit method 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 or C++.)
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 of a container element, in addition to calling back the visit method of the Visitor, also passes the Visitor object to the accept method of all its constituent child elements.