Context:

Some polymorphic processing is configurable and, therefore, may not be part of the processed type family (e.g. formatting, user interface). Processing depends as much on the processor type as on the processed type and must be done by the processor. 

Challenge:

To add the virtual function hierarchy to a class hierarchy without opening it.

Skill:

Participants:

Visitor:

The capability to process the types in a Subject family.

Concrete Visitor:

One implementation of the capability to process a type family, adding a discrete functionality (e.g. formatting, user interface).

Subject:

The capability to forward the visitor to process subject by type. 

Concrete Subject:

Implementation of the capability to forward the visitor to process a concrete subject by type.

Signature:

Visitor processes Subject by requesting Subject to "accept" it (the Visitor). Concrete Subject, requests Visitor to "visit" it (the Concrete Subject).

Used patterns and idioms:

Double-Dispatch idiom.

Used by:

Document/View architectures, dynamically configurable reporting/rendering systems.

Variations:

  • Acyclic visitor . Prevent cyclic namespace dependency by making Visitor a "straw man", separating each Concrete visit-method to pseudo-concrete straw man, assembling the Visitor via multiple inheritance. Accept downcasts. This allows convenient implementation of default behavior. Source: Martin.
  • The above , with straw man parameterized over Concrete Subject type, eliminating cyclic namespace dependency in C++. Source: Alexandrescu.

Known issues:

  1. This pattern is strictly limited to stable hierarchies.
  2. Default visit methods are error-prone unless the funtionality is nice to have.

Scope:

Languages that do not support multi-methods (most commercial OO languages). The Visitor is really a multi-method over Concrete Visitor and Concrete Subject types). Aspect oriented programming attacks the problem by from another direction.