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:
“Working women today are trying to achieve in the work world what men have achieved all alongbut men have always had the help of a woman at home who took care of all the other details of living! Today the working woman is also that woman at home, and without support services in the workplace and a respect for the work women do within and outside the home, the attempt to do both is taking its tollon women, on men, and on our children.”
—Jeanne Elium (20th century)
“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)
“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)