Visitor

Term side of the Card.
Topic: Behavioral Patterns
Unit title: Visitor
Categories: Design pattern
Explanation side of the Card

Explanation: The design pattern that allows new operations to be added to existing object structures without modifying the objects themselves. It centralizes operations in a separate visitor class and promotes the Open-Closed principle.

Example

Wrongjs
class Circle {
  area() { return Math.PI * this.r ** 2; }
  toSvg() { /* ... */ }
  toJson() { /* ... */ }
}
Rightjs
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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy