Visitor
Add new operations to a fixed set of classes without changing them, by putting each operation in its own visitor object.
Description
Visitor flips the usual layout. Instead of adding wordCount() and toHtml() methods to every block class (paragraph, image, table), each operation becomes a visitor class with one method per block type. The blocks only gain a single accept(visitor) method, which calls the right visitor method for itself. That trick is called double dispatch.
Adding an operation is now one new class that touches nothing else. The trade-off is the reverse: adding a new block type means updating every visitor. Visitor fits when the set of types is stable and the set of operations keeps growing, as in compilers, document models and syntax trees.
Class diagram
Visitor pattern class diagram
- Interface Visitor<R> with + visitParagraph(p): R, + visitImage(i): R, + visitTable(t): R.
- Interface Block with + accept(v: Visitor<R>): R.
- Class WordCount with + visit…(): number.
- Class HtmlExport with + visit…(): string.
- Class Paragraph with + accept(v).
- Class Image with + accept(v).
- WordCount implements Visitor<R>.
- HtmlExport implements Visitor<R>.
- Paragraph implements Block.
- Image implements Block.
- Block accepts Visitor<R>.
Sequence diagram
Visitor pattern sequence diagram
- Client → Paragraph: accept(htmlExport).
- Paragraph → HtmlExport: visitParagraph(this).
- Paragraph receives ""<p>…</p>"" back from HtmlExport.
- Client receives ""<p>…</p>"" back from Paragraph.
TypeScript example
A document of paragraphs, images and tables, with two operations, word count and HTML export, each written as a visitor. The block classes never change when a new operation is added. (The diagram omits Table to stay small.)
// Visitor: new operations over a document's blocks (word count, HTML export)
// without adding a method to every block class.
interface Visitor<R> {
visitParagraph(p: Paragraph): R;
visitImage(i: Image): R;
visitTable(t: Table): R;
}
// Element interface: each block "accepts" a visitor
interface Block {
accept<R>(v: Visitor<R>): R;
}
class Paragraph implements Block {
readonly text: string;
constructor(text: string) {
this.text = text;
}
accept<R>(v: Visitor<R>): R {
return v.visitParagraph(this); // double dispatch: the block picks the right method
}
}
class Image implements Block {
readonly src: string;
readonly alt: string;
constructor(src: string, alt: string) {
this.src = src;
this.alt = alt;
}
accept<R>(v: Visitor<R>): R {
return v.visitImage(this);
}
}
class Table implements Block {
readonly rows: string[][];
constructor(rows: string[][]) {
this.rows = rows;
}
accept<R>(v: Visitor<R>): R {
return v.visitTable(this);
}
}
// Concrete visitors: one class per operation, one method per block type
const words = (s: string) => s.split(/\s+/).filter(Boolean).length;
class WordCount implements Visitor<number> {
visitParagraph(p: Paragraph): number {
return words(p.text);
}
visitImage(i: Image): number {
return words(i.alt);
}
visitTable(t: Table): number {
return t.rows.flat().reduce((n, cell) => n + words(cell), 0);
}
}
class HtmlExport implements Visitor<string> {
visitParagraph(p: Paragraph): string {
return `<p>${p.text}</p>`;
}
visitImage(i: Image): string {
return `<img src="${i.src}" alt="${i.alt}">`;
}
visitTable(t: Table): string {
return `<table>${t.rows.map((r) => `<tr>${r.map((c) => `<td>${c}</td>`).join("")}</tr>`).join("")}</table>`;
}
}
export function demo(): string[] {
const doc: Block[] = [
new Paragraph("Quarterly results are in."),
new Image("/chart.png", "Revenue by month"),
new Table([["Q3", "1.2 M"], ["Q4", "1.5 M"]]),
];
const count = new WordCount();
const html = new HtmlExport();
return [`words: ${doc.reduce((n, b) => n + b.accept(count), 0)}`, doc.map((b) => b.accept(html)).join("")];
}When to use it
Use it when
- The class hierarchy is stable, but you keep adding operations over it: export, validate, count, render, transform.
- Operations need type-specific logic for each node in a structure such as an abstract syntax tree, a document model or a scene graph.
- You want related code for one operation together in one place, instead of spread across many classes.
Avoid it when
- New element types are added often. Every visitor must change each time.
- There are one or two operations. Methods on the classes are simpler.
- In TypeScript, a discriminated union with an exhaustive
switchgives the same separation with less ceremony, and the compiler flags missing cases.
Pitfalls
- Visitors that need private data from the elements, which forces you to expose internals. Keep elements' public data sufficient.
- Accumulating state in a visitor between visits and reusing the visitor elsewhere. Return values, or create a fresh visitor per run.
- Unfamiliar to many developers: double dispatch can be hard to follow. Name things plainly and keep the pattern contained.
Alternatives
Discriminated union + switch
Choose it when you write TypeScript: switch (block.kind) with exhaustiveness checking is the idiomatic visitor.
Composite
Choose it when you need the tree structure itself; Visitor is often used on top of it.
Iterator
Choose it when you just need to walk the items, with the same logic for each.
Interpreter
Choose it when evaluation is the one operation and it belongs on the nodes themselves.