Visitor Pattern
Add operations as visitor objects when the kinds of elements in a structure are relatively stable.
· Last updated: 2026-11-07 · 10 min read
Overview
As a document built from text and image nodes takes on rendering, counting, and validation, each new operation scatters code across the node classes. Rather than growing a method on every node for each of them, we pull each operation out into an object of its own.
A visitor is an object with a handling method for each element kind. A rendering visitor collects the rendering code for text and images; a counting visitor collects the code for counting those elements. Each element accepts a visitor and calls the method for its own type, so callers can perform a different operation by changing the visitor while keeping the node structure.
UML
TextNode and ImageNode implement IDocNode and each accept a visitor. TextVisitor implements IVisitor to render the elements, while CountVisitor implements it to count them. Each element class calls the visitor method for its own type; the rendering and counting code stays in the respective visitor classes.
History
GoF cataloged Visitor as a behavioral pattern in Design Patterns in 1994. It separates operations from the classes that form an object structure.1
The mechanical core of Visitor—double dispatch—was formalized at the inaugural OOPSLA conference in 1986, where Daniel H. H. Ingalls showed how a single-dispatch language like Smalltalk can resolve a call across two polymorphic runtime types by chaining two virtual message sends.2
Why use it?
If you want to add rendering or statistics, you add a visitor without touching the existing element code. The element-specific parts of one operation stay together inside a single visitor. Leaving element classes alone cuts the places where existing code can break.
There is a trade-off, though: a new element kind means changing IVisitor and every existing visitor. Where element kinds rarely change and only operations keep growing, that cost stays small. That is why the pattern suits a document model whose node kinds are fixed.
Example
Now we render each document element with TextVisitor.
using System;
using System.Collections.Generic;
using System.Linq;
IDocNode[] nodes = { new TextNode("hello"), new ImageNode("cover") };
var visitor = new TextVisitor();
foreach (IDocNode node in nodes) node.Accept(visitor);
foreach (string line in visitor.Lines) Console.WriteLine(line);
interface IDocNode { void Accept(IVisitor visitor); }
// Collect the element-specific parts of one operation in its visitor.
interface IVisitor
{
void Visit(TextNode node);
void Visit(ImageNode node);
}
// The node selects its matching visitor method without implementing the operation itself.
sealed record TextNode(string Value) : IDocNode
{
public void Accept(IVisitor visitor) => visitor.Visit(this);
}
sealed record ImageNode(string Name) : IDocNode
{
public void Accept(IVisitor visitor) => visitor.Visit(this);
}
sealed class TextVisitor : IVisitor
{
public List<string> Lines { get; } = new();
public void Visit(TextNode node) => Lines.Add(node.Value);
public void Visit(ImageNode node) => Lines.Add("[image: " + node.Name + "]");
}
sealed class CountVisitor : IVisitor
{
public int Texts { get; private set; }
public int Images { get; private set; }
public void Visit(TextNode node) => Texts++;
public void Visit(ImageNode node) => Images++;
}
hello
[image: cover]In the caller, node is typed IDocNode, so Visit(node) alone cannot tell the TextNode case from the ImageNode case. That choice falls to each Accept(), which passes its own concrete this to Visit() and connects it to the matching handling, so the caller needs no per-element branching. All the caller knows is IDocNode; the concrete type is known to the element itself.
An extended example
This time the element classes stay as they are; a second operation, CountVisitor, counts text nodes and image nodes.
The first example asks how to represent the document's contents. This example asks which kinds of elements the document contains. Mixing two text nodes with one image makes it easy to see one traversal perform different counting operations for different element types.
Accept on TextNode("hello") calls Visit(TextNode), raising Texts to 1. The image calls Visit(ImageNode), raising only Images to 1, and TextNode("world") then raises Texts to 2. The traversal keeps calling the same Accept method; the two methods in CountVisitor decide what to count.
using System;
using System.Collections.Generic;
using System.Linq;
IDocNode[] nodes = { new TextNode("hello"), new ImageNode("cover"), new TextNode("world") };
var visitor = new CountVisitor();
foreach (IDocNode node in nodes) node.Accept(visitor);
Console.WriteLine("text nodes: " + visitor.Texts);
Console.WriteLine("image nodes: " + visitor.Images);
interface IDocNode { void Accept(IVisitor visitor); }
// Collect the element-specific parts of one operation in its visitor.
interface IVisitor
{
void Visit(TextNode node);
void Visit(ImageNode node);
}
// The node selects its matching visitor method without implementing the operation itself.
sealed record TextNode(string Value) : IDocNode
{
public void Accept(IVisitor visitor) => visitor.Visit(this);
}
sealed record ImageNode(string Name) : IDocNode
{
public void Accept(IVisitor visitor) => visitor.Visit(this);
}
sealed class TextVisitor : IVisitor
{
public List<string> Lines { get; } = new();
public void Visit(TextNode node) => Lines.Add(node.Value);
public void Visit(ImageNode node) => Lines.Add("[image: " + node.Name + "]");
}
sealed class CountVisitor : IVisitor
{
public int Texts { get; private set; }
public int Images { get; private set; }
public void Visit(TextNode node) => Texts++;
public void Visit(ImageNode node) => Images++;
}
text nodes: 2
image nodes: 1Traversal belongs to the foreach in the caller, and the visitor owns only what to do with each element. The same holds when you attach it to a Composite tree: unless you decide up front who owns traversal of the children, the same node ends up visited twice. A visitor does not choose the next element, so moving traversal into it mixes two responsibilities.
TypeScript example
Here too the nodes only connect their own kind to the visitor, while operations such as rendering and counting live on the visitor side. The split exists so that adding a new operation does not mean growing a method in every node class. The class structure matches the C# example; the language differences come later.
interface IDocNode { accept(visitor: IVisitor): void; }
// Collect the element-specific parts of one operation in its visitor.
interface IVisitor {
visitText(node: TextNode): void;
visitImage(node: ImageNode): void;
}
// The node selects its matching visitor method without implementing the operation itself.
class TextNode implements IDocNode {
constructor(readonly text: string) {}
accept(visitor: IVisitor): void { visitor.visitText(this); }
}
class ImageNode implements IDocNode {
constructor(readonly caption: string) {}
accept(visitor: IVisitor): void { visitor.visitImage(this); }
}
class TextVisitor implements IVisitor {
readonly lines: string[] = [];
visitText(node: TextNode): void { this.lines.push(node.text); }
visitImage(node: ImageNode): void { this.lines.push("[image: " + node.caption + "]"); }
}
class CountVisitor implements IVisitor {
texts = 0;
images = 0;
visitText(node: TextNode): void { this.texts++; }
visitImage(node: ImageNode): void { this.images++; }
}
const nodes: IDocNode[] = [new TextNode("hello"), new ImageNode("cover"), new TextNode("world")];
const render = new TextVisitor();
const count = new CountVisitor();
for (const node of nodes) { node.accept(render); node.accept(count); }
for (const line of render.lines) console.log(line);
console.log("text nodes: " + count.texts);
console.log("image nodes: " + count.images);hello
[image: cover]
world
text nodes: 2
image nodes: 1In TypeScript an overload declaration serves type checking, and there is only one actual implementation. This version therefore splits the C# Visit(TextNode) and Visit(ImageNode) into visitText and visitImage, and each accept() calls the one that matches its own type. The caller does the same work as in the C# example.
How double dispatch works and the Expression Problem
Why must callers write node.Accept(visitor) instead of calling visitor.Visit(node) directly? Because in single-dispatch languages like C#, Java, and C++, virtual method lookup inspects the runtime type of the receiver before the dot (.) only, whereas overload resolution for arguments inside the parentheses is locked in at compile time using the static type IDocNode (see Polymorphism). Stepping through node.Accept(visitor) performs the first dynamic dispatch into TextNode.Accept, where the static type of this is now known to be TextNode; calling visitor.Visit(this) from there binds to the Visit(TextNode) overload and performs the second dynamic dispatch.
In 1998 Philip Wadler framed this fundamental trade-off as the Expression Problem.3 Ordinary object-oriented classes group operations by data variant, making it easy to add new node classes but painful to add new operations across all of them. Visitor—like pattern matching over algebraic sum types—flips the matrix: adding a new operation is as easy as writing a new Visitor class, whereas adding a new node variant forces every existing Visitor to implement a new method. Visitor is therefore the right tool when the set of element types is stable and the set of passes over them keeps growing.
Related reading
Footnotes
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). Publisher record. Behavioral patterns, Visitor. ↩
- Daniel H. H. Ingalls, "A Simple Technique for Handling Multiple Polymorphism," OOPSLA '86 Proceedings, ACM, 1986, pp. 347–349. DOI. ↩
- Philip Wadler, "The Expression Problem," Java Genericity mailing list note, November 12, 1998. Archive. ↩