Visitor Pattern - Details

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:

    Anyone can see that to write Uncle Tom’s 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 (1851–1931)

    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)

    Working women today are trying to achieve in the work world what men have achieved all along—but 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 toll—on women, on men, and on our children.
    Jeanne Elium (20th century)