Details
The visitor pattern requires a programming language that supports single dispatch and method overloading. Under these conditions, consider two objects, each of some class type; one is called the "element", and the other is called the "visitor". An element has an accept
method that can take the visitor as an argument. The accept
method calls a visit
method of the visitor; the element passes itself as an argument to the visit
method. Thus:
- 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.
- This effectively implements double dispatch; indeed, because the Lisp language's object system supports multiple dispatch (not just single dispatch), implementing the visitor pattern in Lisp is trivial.
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.
Read more about this topic: Visitor Pattern
Famous quotes containing the word details:
“Different persons growing up in the same language are like different bushes trimmed and trained to take the shape of identical elephants. The anatomical details of twigs and branches will fulfill the elephantine form differently from bush to bush, but the overall outward results are alike.”
—Willard Van Orman Quine (b. 1908)
“Patience is a most necessary qualification for business; many a man would rather you heard his story than granted his request. One must seem to hear the unreasonable demands of the petulant, unmoved, and the tedious details of the dull, untired. That is the least price that a man must pay for a high station.”
—Philip Dormer Stanhope, 4th Earl Chesterfield (16941773)