Visitor
Category
Behavioral pattern
Problem
Represent a new operation to be performed on elements of an object structure without changing the classes of the elements. Useful when you need to perform many different operations on a complex object structure and want to keep the operations separate from the object classes.
Solution
- Create a Visitor interface with a
visit()method for each concrete element type - Each concrete element implements an
accept()method that calls the visitor - The visitor performs the operation, accessing the element’s internal state
Structure
- Visitor: Declares a visit operation for each element type
- ConcreteVisitor: Implements operations for each element type
- Element: Declares an
accept()method that takes a visitor - ConcreteElement: Implements
accept()to call the visitor’s operation - ObjectStructure: Can enumerate its elements; may provide a high-level interface to accept visitors
Key Benefits
- Adds new operations easily — New visitors can be added without modifying element classes
- Groups related operations — Related operations are in one visitor class
- Accumulates state — Visitors can accumulate state across visits
Trade-offs
- Hard to add new element types — Requires changes to the Visitor interface and all concrete visitors
- Violates encapsulation — Visitors often need access to internal state of elements
When to Use
- An object structure contains many classes with differing interfaces, and you need to perform operations that depend on their concrete classes
- You need to perform many unrelated operations on elements of a structure
- You want to add new operations without changing the element classes