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:
“There was a time when the average reader read a novel simply for the moral he could get out of it, and however naïve that may have been, it was a good deal less naïve than some of the limited objectives he has now. Today novels are considered to be entirely concerned with the social or economic or psychological forces that they will by necessity exhibit, or with those details of daily life that are for the good novelist only means to some deeper end.”
—Flannery OConnor (19251964)
“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)