design patterns · behavioral
Visitor
Lets you add new operations to existing object structures without modifying the classes of those objects.
Pattern
Overview
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.
Real-World Analogy
A tax auditor (visitor) visits different business entities (companies, individuals) applying tax rules to each without changing how entities are structured.
When you have a stable set of element classes but frequently need to add new operations on them, Visitor lets you add the operations externally without touching the element classes.
Element classes implement accept(Visitor). They call visitor.visit(this) - passing themselves to the visitor. The Visitor has an overloaded visit() method for each Element type, implementing the specific operation.
When to use
AST traversal in compilers, document export (HTML/PDF/XML from the same DOM), tax calculation over product types, static analysis tools, report generation over heterogeneous collections.
When not to
When the element class hierarchy frequently changes - Visitor requires updating all visitors for each new element. When the operations are simple - direct methods on elements are clearer.
Participants
Key Insights
- Double dispatch: first dispatch on element type (accept), second dispatch on visitor type (visit)
- Visitor works best when the element hierarchy is stable but operations change frequently
- The element hierarchy stability constraint is the key trade-off vs extending element classes directly
- Java compiler's AST traversal uses Visitor extensively