Visitor Design Pattern
Behavioral pattern. Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects.
The Visitor design pattern solves problems like: How can new operations be defined for the classes of an object structure without changing the classes?
Open in the interactive referenceDownload the PDF reference
Solution
The Visitor design pattern provides a solution:
Define a separate
Visitor
object that implements operations
to be performed
on the elements of
an object structure.
Clients traverse the object structure
and call
accept(visitor) on each element
to delegate the request
to the "accepted visitor object".
The visitor object then performs the request
("visits" the element).
Describing the Visitor design in more detail is the theme
of the following sections.
See Applicability section for all problems Visitor can solve.
-
The key idea in this pattern is to define a double-dispatch
operation
accept(visitor)for eachElementclass (see also Collaboration and Implementation).
"This is the key to the Visitor pattern. The operation that gets executed depends on both the type of Visitor and the type of Element it visits." [GoF, p339] -
Define separate
Visitorobjects:-
For all supported
Elementclasses, define a commonVisitorinterface by defining a "visit" operation for eachElementclass (Visitor | visitElementA(e),visitElementB(e),…).
"We'll use the term visitor to refer generally to classes of objects that "visit" other objects during a traversal and do something appropriate." [GoF, p74] -
Define classes (
Visitor1,…) that implement theVisitorinterface.
-
For all supported
-
This enables compile-time flexibility (via class inheritance).
"You create a new operation by adding a new subclass to the visitor class hierarchy." [GoF, p333]
Applicability
Design Problems
-
Defining New Operations for Object Structures
-
How can new operations be defined for the classes of
an object structure
without changing the classes?
-
How can new operations be defined for the classes of
an object structure
without changing the classes?
-
Flexible Alternative to Subclassing
-
How can a flexible alternative be provided to subclassing
for defining new operations for the classes of an object structure?
-
How can a flexible alternative be provided to subclassing
Not included on this page: Intent, Problem, Motivation, Structure, Consequences, Implementation, Related Patterns. See the GoF Design Patterns Reference (PDF) for the complete description.