Origin: | GoF 95 | ||||||||||
Reason: | To define new operations on the objects of a structure (as in a Composite) without changing the objects. | ||||||||||
Synopsis: | Each object, say obj, of the structure defines a method, conventionally called accept, that takes an object conventially called a visitor. The visitor, rather than obj, implements the new operation. Method accept dispatches the execution of the operation to the visitor. | ||||||||||
Example: | A document for word processing is a Composite whose nodes are paragraphs, lines, images, etc. To create the table of content of a document one can define an operation in each node class. The Visitor pattern allows one to define these operations in a separate, dedicated object. | ||||||||||
Solution: |
|
||||||||||
See also: |
Composite
(often the object to be visited) Little Language (often uses visitors) |
||||||||||
Note: |
This is a complicated pattern that requires a good understanding
of the concepts of overloading and overriding.
The following code sketches the key elements of this pattern.
Interface of all visitable objects. Visitable classes. The type of "this" is bound at compile time. Interface of all visitors. Actual visitor class. Implements an operation that would otherwise be a member of each Element_i. Sometimes methods accept and visit take one extra argument, an Object, and return a value, an Object. |