Visitor

Visitor

Intent

Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Applicability

Use visitor pattern when:

  • An object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes.
  • many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid polluting their classes with these operations.
  • the classes defining the object structure rarely change, but you often want to define new operations over the structure.

Structure

Orange

Participants

  • Visitor: declares a Visit operation for each class of ConcreteElement in the object structure.
  • ConcreteVisitor: implements each operation declared by Visitor.
  • Element: defines an Accept operation that takes a visitor as an argument.
  • ConcreteElement: implements an Accept operation that takes a visitor as an argument.
  • ObjectStructure: can enumerate it's elements, may provide a high-level interface to allow the visitor to visit it's elements.

Collaborations

  • A client that uses the Visitor pattern must create a ConcreteVisitor object and then traverse the object structure, visiting each element with the visitor.
  • When an element is visited, it calls the Visitor operation that corresponds to it's class.

Consequences

  • Visitor makes adding new operations easy.
  • A visitor gathers related operations and separates unrelated ones.
  • Adding new ConcreteElement classes is hard.

Sample Code

Visitor

Related Patterns

  • Composite: Visitors can be used to apply sn operation over an object structure defined by the Composite pattern.
  • Interpreter: Visitor may be applied to do the interpretation.