Visitor

Intent

Represent 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.

Sequence Diagram

Examples

Tree traversals and graph searches are both general examples of the Visitor design pattern.

Tree Traversals

Graph Searches

Document Object Model (DOM) and Simple API for XML (SAX) are two schemes for dealing with XML structured documents. While DOM builds a Composite structure for an XML document, SAX implements the Visitor design pattern. Curiously, there is no built-in Visitor implementation in the DOM structures.

Notes

Concrete visitors can have state that is updated during a traversal. They will usually have methods beyond the visitor interface that accesses this state to return results of a traversal.

The most general Visitor interface can be considered to be event-driven. The Object Structure implements a traversal and invokes Visitor methods for both entering and leaving internal (non-leaf) nodes in a hierarchical structure.

The Visitor design pattern is more generally a pattern for double dispatch. Many object-oriented languages only provide single dispatch: the code that is executed for a message only depends on the receiver. With double dispatch the code that is executed depends also on a parameter of the message. A few object-oriented languages (Scala for example) can dispatch based on several parameters.

Structure

Participants