Visitor Idea
The Visitor pattern separates structure traversal from operations: elements call accept(visitor), and the visitor defines visit methods for each node type.
Useful when many operations are performed on stable structures (such as compiler ASTs, document trees).
Separate operation from structure: ElementVisitor [1].
Where used
Compiler frontends, serialization over ASTs, operations on stable object graphs without needing to open node types constantly.
Depth
The Visitor pattern encapsulates operations in visitor classes, while elements of a heterogeneous structure provide an accept method. By calling visitor.visit(this), both the concrete visitor type and the concrete element type are taken into account in method selection.
New operations can be added without having to fill each element class with additional domain logic. However, new element types are costly since all existing visitor interfaces and implementations need to be extended. Therefore, the pattern fits stable element hierarchies with varying evaluations.
Difficulty levels
- Track accept and visit in a small class model.
- Explain double dispatch compared to simple overriding.
- Compare extension costs for new operations and new elements.
Pitfalls
A visitor is not just a collection of instanceof checks. If such case distinctions are maintained centrally, type safety and the actual dispatch advantage are lost.
Sources
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Beginner
- Completed: 0 users