Design Patterns

Pattern 22 of 23, Behavioral family

Visitor

Separate an algorithm from the object structure it operates on, so you can add operations without modifying those classes.

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
  1. The client passes a visitor to each element.
  2. Double dispatch: Circle calls the visitor method that matches it.
  3. Client โ†’ Rect (10 ร— 5): accept(visitor)
  4. Rect (10 ร— 5) โ†’ AreaVisitor ฮฃ = 78.5: visitRect(this)
  5. New operation = new visitor. Circle and Rect stay untouched.
  6. Client โ†’ Circle (r = 5): accept(json)
  7. โ†’ {"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

visitor.py 34 lines
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

visitor.ts 31 lines
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

visitor.java 29 lines
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#

visitor.cs 26 lines
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

visitor.php 28 lines
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

visitor.go 22 lines
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.