Visitor
Example
class Circle {
area() { return Math.PI * this.r ** 2; }
toSvg() { /* ... */ }
toJson() { /* ... */ }
}const areaVisitor = {
circle: (s) => Math.PI * s.r ** 2,
rect: (s) => s.w * s.h,
};
const visit = (shape, visitor) => visitor[shape.kind](shape);
visit({ kind: 'rect', w: 2, h: 3 }, areaVisitor);Each operation lives in its own visitor keyed by node type, so shapes stay unchanged as new operations are added.
Common mistakes
- Adding a method to every class for each new operation.
- A visitor that silently ignores node types it doesn't know.
Key points
- The visitor has a handler for every node type, and an unknown type throws instead of being skipped silently.
- New operations are added as new visitors without editing the node classes.
- In TypeScript, node types form a discriminated union so a missing handler is a type error.
Interview questions
Where is the Visitor pattern used in practice?
Compilers, linters and code transformers walk syntax trees with visitors that have one handler per node type.
What is the downside of the Visitor pattern?
Adding a new node type is hard: every existing visitor must get a new handler. It suits stable structures with frequently added operations.
What is double dispatch in Visitor?
The node calls visitor.visitX(this) from its accept method, so the chosen code depends on both the node type and the visitor type.