Visitor
Intent
Separates algorithms from the objects on which they operate.
Problem
You need to export a graph of nodes to XML, then JSON, then calculate metrics, without editing node classes each time.
Solution
Put each operation in a visitor class with one method per element type; elements accept a visitor (double dispatch).
Real-world analogy
An insurance agent visiting a street: a home gets home insurance, a bank gets theft insurance, a shop gets fire insurance.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Visitor — Visitor declares one visit method per concrete element type.
- 2ConcreteVisitors — Concrete Visitors implement one operation for every element type.
- 3Element — Element declares accept(), which takes a visitor.
- 4ElementA — Concrete Elements call the visit method that matches their own class (double dispatch).
Code example
Applicability
Use Visitor when performing an operation on all elements of a complex structure.
Use Visitor when keeping auxiliary behaviour out of domain classes.
Pros and cons
Pros
- Open–Closed for operations
- Accumulates state while traversing
Cons
- Every visitor changes when an element type is added
Check yourself
Add an export-to-JSON operation across a hierarchy of syntax-tree node classes without modifying them.
Saved in this browser only. Part of Behavioral patterns (0/11).