Visitor

Gamma et al. 95

Intent

To represent an operation that will be performed on an object structure.
The visitor pattern allows you to define a new operation without changing the classes on which it is performed.

Motivation (1/3)

  • Example: a compiler

  • Several different operations can be applied to this structure: type checking, optimization, etc.

visitor motivation

Motivation (2/3)

  • These operations are defined in a separate structure

visitor example

Motivation (3/3)

visitor motivation collaboration

Applicability

Use the Visitor pattern when:
  • you need to perform an operation on a structure of objects belonging to different classes.

  • several heterogeneous operations apply to these objects, and you do not want to "clutter" the classes with these operations. the structure does not change.

Structure

visitor structure

Collaborations

visitor collaboration

Consequences

  • Adding new operations is simplified.

  • The user groups related operations together and isolates them from others.

  • Adding a new Element to the structure becomes complex.

  • Accumulation of values.

  • Encapsulation is violated.

Implementation Trade-offs

  • Double dispatch (CLOS, Dylan):
    The operation performed depends on the provider and the client.

  • Who is responsible for traversing the structure?
    The structure itself, the visitor, or an iterator?

Useful links

Author and Date

  • Design Patterns: Elements of Reusable Object-Oriented Software. Erich Gamma, Richard Helm,Ralph Johnson, and John Vlissides. Addison Wesley. October 1994.