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:

    Then he told the news media
    the strange details of his death
    and they hammered him up in the marketplace
    and sold him and sold him and sold him.
    My death the same.
    Anne Sexton (1928–1974)

    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)