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)
“Anyone can see that to write Uncle Toms Cabin on the knee in the kitchen, with constant calls to cooking and other details of housework to punctuate the paragraphs, was a more difficult achievement than to write it at leisure in a quiet room.”
—Anna Garlin Spencer (18511931)
“If my sons are to become the kind of men our daughters would be pleased to live among, attention to domestic details is critical. The hostilities that arise over housework...are crushing the daughters of my generation....Change takes time, but mens continued obliviousness to home responsibilities is causing women everywhere to expire of trivialities.”
—Mary Kay Blakely (20th century)