Visitor
Separate an algorithm from the object structure it operates on, so you can add operations without modifying those classes.
- 7 animated steps
- 6 languages
- Behavioral patterns
The problem
You have shapes (Circle, Rectโฆ) and you keep having to add operations: area, JSON export, SVG renderingโฆ Modifying every class each time violates Open/Closed.
The solution
Each element exposes accept(visitor), which calls back the right method on the visitor (visitCircle(this)): that is double dispatch. A new operation = a new visitor.
The pattern in action
- Client
- Key role of the pattern
- Object
- Data or state
- The client passes a visitor to each element.
- Double dispatch: Circle calls the visitor method that matches it.
- Client โ Rect (10 ร 5): accept(visitor)
- Rect (10 ร 5) โ AreaVisitor ฮฃ = 78.5: visitRect(this)
- New operation = new visitor. Circle and Rect stay untouched.
- Client โ Circle (r = 5): accept(json)
- โ {"type": "circle", "r": 5}
An analogy
An insurance agent visits a house, a factory, a shop: they tailor their offer to the type of building, without the buildings changing.
When to use it
- Stable structure, operations added frequently
- ASTs: compilers, linters, formatters
- Multiple exports (JSON, XML, PDF)
Pros and cons
Pros
- Add an operation without touching the classes
- The logic of an operation gathered in one place
Cons
- Adding a new element type forces you to modify every visitor
- Can break encapsulation
- Often replaced by modern pattern matching
Implementations
The same example, written idiomatically in each language.
Visitor in Python
import math
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def accept(self, v): ...
class Circle(Shape):
def __init__(self, r): self.r = r
def accept(self, v): return v.visit_circle(self)
class Rect(Shape):
def __init__(self, w, h): self.w, self.h = w, h
def accept(self, v): return v.visit_rect(self)
class AreaVisitor:
def visit_circle(self, c): return math.pi * c.r ** 2
def visit_rect(self, r): return r.w * r.h
class JsonVisitor:
def visit_circle(self, c): return {"type": "circle", "r": c.r}
def visit_rect(self, r): return {"type": "rect", "w": r.w, "h": r.h}
shapes = [Circle(5), Rect(10, 5)]
print(sum(s.accept(AreaVisitor()) for s in shapes)) # 128.54
print([s.accept(JsonVisitor()) for s in shapes])
# Python 3.10+: "match shape: case Circle(r=r): ..." is often simpler
Visitor in TypeScript
interface Visitor<R> {
circle(c: Circle): R;
rect(r: Rect): R;
}
interface Shape {
accept<R>(v: Visitor<R>): R;
}
class Circle implements Shape {
constructor(public r: number) {}
accept<R>(v: Visitor<R>) { return v.circle(this); }
}
class Rect implements Shape {
constructor(public w: number, public h: number) {}
accept<R>(v: Visitor<R>) { return v.rect(this); }
}
const area: Visitor<number> = {
circle: (c) => Math.PI * c.r ** 2,
rect: (r) => r.w * r.h,
};
const toJson: Visitor<object> = {
circle: (c) => ({ type: "circle", r: c.r }),
rect: (r) => ({ type: "rect", w: r.w, h: r.h }),
};
const shapes: Shape[] = [new Circle(5), new Rect(10, 5)];
shapes.reduce((sum, s) => sum + s.accept(area), 0);
Visitor in Java
interface ShapeVisitor<R> {
R visitCircle(Circle c);
R visitRect(Rect r);
}
sealed interface Shape permits Circle, Rect {
<R> R accept(ShapeVisitor<R> v);
}
record Circle(double r) implements Shape {
public <R> R accept(ShapeVisitor<R> v) { return v.visitCircle(this); }
}
record Rect(double w, double h) implements Shape {
public <R> R accept(ShapeVisitor<R> v) { return v.visitRect(this); }
}
class AreaVisitor implements ShapeVisitor<Double> {
public Double visitCircle(Circle c) { return Math.PI * c.r() * c.r(); }
public Double visitRect(Rect r) { return r.w() * r.h(); }
}
// Java 21: exhaustive pattern matching often replaces the Visitor
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.r() * c.r();
case Rect r -> r.w() * r.h();
};
}
Visitor in C#
interface IShapeVisitor<out T>
{
T Visit(Circle c);
T Visit(Rect r);
}
interface IShape { T Accept<T>(IShapeVisitor<T> v); }
record Circle(double R) : IShape
{
public T Accept<T>(IShapeVisitor<T> v) => v.Visit(this);
}
record Rect(double W, double H) : IShape
{
public T Accept<T>(IShapeVisitor<T> v) => v.Visit(this);
}
class AreaVisitor : IShapeVisitor<double>
{
public double Visit(Circle c) => Math.PI * c.R * c.R;
public double Visit(Rect r) => r.W * r.H;
}
IShape[] shapes = [new Circle(5), new Rect(10, 5)];
var total = shapes.Sum(s => s.Accept(new AreaVisitor()));
Visitor in PHP
interface ShapeVisitor
{
public function visitCircle(Circle $c): mixed;
public function visitRect(Rect $r): mixed;
}
interface Shape { public function accept(ShapeVisitor $v): mixed; }
final class Circle implements Shape
{
public function __construct(public float $r) {}
public function accept(ShapeVisitor $v): mixed { return $v->visitCircle($this); }
}
final class Rect implements Shape
{
public function __construct(public float $w, public float $h) {}
public function accept(ShapeVisitor $v): mixed { return $v->visitRect($this); }
}
final class AreaVisitor implements ShapeVisitor
{
public function visitCircle(Circle $c): float { return M_PI * $c->r ** 2; }
public function visitRect(Rect $r): float { return $r->w * $r->h; }
}
$shapes = [new Circle(5), new Rect(10, 5)];
echo array_sum(array_map(fn(Shape $s) => $s->accept(new AreaVisitor()), $shapes));
Visitor in Go
type Visitor interface {
VisitCircle(c Circle) float64
VisitRect(r Rect) float64
}
type Shape interface{ Accept(v Visitor) float64 }
type Circle struct{ R float64 }
func (c Circle) Accept(v Visitor) float64 { return v.VisitCircle(c) }
type Rect struct{ W, H float64 }
func (r Rect) Accept(v Visitor) float64 { return v.VisitRect(r) }
type AreaVisitor struct{}
func (AreaVisitor) VisitCircle(c Circle) float64 { return math.Pi * c.R * c.R }
func (AreaVisitor) VisitRect(r Rect) float64 { return r.W * r.H }
// Idiomatic alternative in Go: the type switch
// switch s := shape.(type) { case Circle: โฆ; case Rect: โฆ }
Frequently asked questions
What is the Visitor design pattern?
Separate an algorithm from the object structure it operates on, so you can add operations without modifying those classes. Each element exposes accept(visitor), which calls back the right method on the visitor (visitCircle(this)): that is double dispatch. A new operation = a new visitor.
When should you use the Visitor pattern?
Stable structure, operations added frequently; ASTs: compilers, linters, formatters; Multiple exports (JSON, XML, PDF).
What are the pros and cons of the Visitor pattern?
Pros: Add an operation without touching the classes; The logic of an operation gathered in one place. Cons: Adding a new element type forces you to modify every visitor; Can break encapsulation; Often replaced by modern pattern matching.