Article · Visitor
Visitor: new operations without changing classes
The Visitor pattern through a menu: dishes, drinks and sets stay untouched, while pricing, an allergen report or an export are separate visitor objects. Double dispatch, a comparison with pattern matching and code in five languages.
The menu of Halina's pierogi place is a tree: dishes, drinks and sets that contain further items. Several teams work on the same structure: accounting calculates prices, the health inspector wants an allergen report, the delivery app wants an export in its own format. Visitor lets you add such operations as separate objects, without writing yet more methods into the dish classes.
- 3
- menu item types – dish, drink, set
- 2
- operations in the example – price and allergen report
- 0
- changes in the menu classes – when another operation is added
The problem: classes that do everything for everyone
Every new need ended with a new method in the menu classes:
class Dish {
constructor(public name: string, public price: number, public allergens: string[]) {}
totalPrice(): number { return this.price; }
allergenList(): string[] { return this.allergens; }
toPrintCard(): string { /* typography for the printed menu */ }
toDeliveryAppJson(): object { /* the format required by the delivery app */ }
vatReportLine(): string { /* accounting */ }
}
// ...and the same five methods in Drink and Combo – each one owned by a different teamThe Dish class knows the typography of the printed menu, the delivery app's format and accounting rules. Every team modifies the same three files, and a change to the export means retesting prices. The logic of one operation – the VAT report, for example – is smeared across three classes, so it is hard to read as a whole.
The solution: the operation comes to the data
Visitor flips the arrangement. Menu classes get one method, accept(visitor), and know nothing else about operations. Each operation is a class implementing the MenuVisitor interface with a method for every item type: visitDish, visitDrink, visitCombo. All the pricing logic goes into PriceVisitor, all the allergen logic into AllergenVisitor.
| Role | In the example | Responsibility |
|---|---|---|
| Visitor | MenuVisitor | a method for each element type |
| Concrete visitor | PriceVisitor, AllergenVisitor | one operation over the whole structure |
| Element | MenuItem | the accept(visitor) method |
| Concrete element | Dish, Drink, Combo | in accept calls the visitor method for its own type |
| Object structure | the item list, sets | the collection of elements to visit |
Implementation in five languages
In C# and Java the visitor methods are visit(...) overloads – the compiler picks the right one based on the static type of this inside accept. TypeScript, Go and Python have no overloading, so the methods have different names (visitDish, VisitDish, visit_dish). Notice that the visitors decide how to walk the contents of a set – PriceVisitor sums it separately in order to apply the discount.
Visitor – operations on the menu
IMenuItem[] menu =
[
new Combo("Lunch set", 0.10m,
[
new Dish("Ruskie", 28m, ["gluten", "milk"]),
new Dish("Soup of the day", 14m, ["celery"]),
new Drink("Kompot", 8m, 0.3m),
]),
new Dish("With black pudding", 35m, ["gluten"]),
new Drink("Lemonade", 12m, 0.5m),
];
var prices = new PriceVisitor();
var allergens = new AllergenVisitor();
foreach (var item in menu) { item.Accept(prices); item.Accept(allergens); }
Console.WriteLine($"Total: {prices.Total} PLN"); // Total: 92.00 PLN
Console.WriteLine($"Allergens: {string.Join(", ", allergens.Found)}"); // celery, gluten, milk
public interface IMenuVisitor
{
void Visit(Dish dish);
void Visit(Drink drink);
void Visit(Combo combo);
}
public interface IMenuItem
{
void Accept(IMenuVisitor visitor);
}
// Double dispatch: the item's own type picks the right Visit overload.
public sealed record Dish(string Name, decimal Price, string[] Allergens) : IMenuItem
{
public void Accept(IMenuVisitor v) => v.Visit(this);
}
public sealed record Drink(string Name, decimal Price, decimal Litres) : IMenuItem
{
public void Accept(IMenuVisitor v) => v.Visit(this);
}
public sealed record Combo(string Name, decimal Discount, IMenuItem[] Items) : IMenuItem
{
public void Accept(IMenuVisitor v) => v.Visit(this);
}
// A new operation is a new visitor – the menu classes stay untouched.
public sealed class PriceVisitor : IMenuVisitor
{
public decimal Total { get; private set; }
public void Visit(Dish dish) => Total += dish.Price;
public void Visit(Drink drink) => Total += drink.Price;
public void Visit(Combo combo)
{
var inner = new PriceVisitor();
foreach (var item in combo.Items) item.Accept(inner);
Total += Math.Round(inner.Total * (1 - combo.Discount), 2);
}
}
public sealed class AllergenVisitor : IMenuVisitor
{
public SortedSet<string> Found { get; } = [];
public void Visit(Dish dish) => Found.UnionWith(dish.Allergens);
public void Visit(Drink drink) { }
public void Visit(Combo combo) { foreach (var item in combo.Items) item.Accept(this); }
}interface MenuVisitor {
visitDish(dish: Dish): void;
visitDrink(drink: Drink): void;
visitCombo(combo: Combo): void;
}
interface MenuItem {
accept(visitor: MenuVisitor): void;
}
// Double dispatch: each item calls the visitor method meant for its own type.
class Dish implements MenuItem {
constructor(readonly name: string, readonly price: number, readonly allergens: string[]) {}
accept(v: MenuVisitor): void { v.visitDish(this); }
}
class Drink implements MenuItem {
constructor(readonly name: string, readonly price: number, readonly litres: number) {}
accept(v: MenuVisitor): void { v.visitDrink(this); }
}
class Combo implements MenuItem {
constructor(readonly name: string, readonly discount: number, readonly items: MenuItem[]) {}
accept(v: MenuVisitor): void { v.visitCombo(this); }
}
// A new operation is a new visitor – the menu classes stay untouched.
class PriceVisitor implements MenuVisitor {
total = 0;
visitDish(d: Dish) { this.total += d.price; }
visitDrink(d: Drink) { this.total += d.price; }
visitCombo(c: Combo) {
const inner = new PriceVisitor();
c.items.forEach((i) => i.accept(inner));
this.total += Math.round(inner.total * (1 - c.discount) * 100) / 100;
}
}
class AllergenVisitor implements MenuVisitor {
readonly found = new Set<string>();
visitDish(d: Dish) { d.allergens.forEach((a) => this.found.add(a)); }
visitDrink() {}
visitCombo(c: Combo) { c.items.forEach((i) => i.accept(this)); }
}
const menu: MenuItem[] = [
new Combo('Lunch set', 0.1, [
new Dish('Ruskie', 28, ['gluten', 'milk']),
new Dish('Soup of the day', 14, ['celery']),
new Drink('Kompot', 8, 0.3),
]),
new Dish('With black pudding', 35, ['gluten']),
new Drink('Lemonade', 12, 0.5),
];
const prices = new PriceVisitor();
const allergens = new AllergenVisitor();
menu.forEach((item) => { item.accept(prices); item.accept(allergens); });
console.log(prices.total, [...allergens.found].sort()); // 92 [ 'celery', 'gluten', 'milk' ]import java.util.List;
import java.util.TreeSet;
interface MenuVisitor {
void visit(Dish dish);
void visit(Drink drink);
void visit(Combo combo);
}
sealed interface MenuItem permits Dish, Drink, Combo {
void accept(MenuVisitor visitor);
}
// Double dispatch: inside accept() the static type of "this" picks the overload.
record Dish(String name, double price, List<String> allergens) implements MenuItem {
public void accept(MenuVisitor v) { v.visit(this); }
}
record Drink(String name, double price, double litres) implements MenuItem {
public void accept(MenuVisitor v) { v.visit(this); }
}
record Combo(String name, double discount, List<MenuItem> items) implements MenuItem {
public void accept(MenuVisitor v) { v.visit(this); }
}
// A new operation is a new visitor – the menu classes stay untouched.
class PriceVisitor implements MenuVisitor {
double total;
public void visit(Dish d) { total += d.price(); }
public void visit(Drink d) { total += d.price(); }
public void visit(Combo c) {
var inner = new PriceVisitor();
c.items().forEach(i -> i.accept(inner));
total += Math.round(inner.total * (1 - c.discount()) * 100) / 100.0;
}
}
class AllergenVisitor implements MenuVisitor {
final TreeSet<String> found = new TreeSet<>();
public void visit(Dish d) { found.addAll(d.allergens()); }
public void visit(Drink d) {}
public void visit(Combo c) { c.items().forEach(i -> i.accept(this)); }
}
public class MenuVisitors {
public static void main(String[] args) {
List<MenuItem> menu = List.of(
new Combo("Lunch set", 0.10, List.of(
new Dish("Ruskie", 28, List.of("gluten", "milk")),
new Dish("Soup of the day", 14, List.of("celery")),
new Drink("Kompot", 8, 0.3))),
new Dish("With black pudding", 35, List.of("gluten")),
new Drink("Lemonade", 12, 0.5));
var prices = new PriceVisitor();
var allergens = new AllergenVisitor();
menu.forEach(i -> { i.accept(prices); i.accept(allergens); });
System.out.println(prices.total + " PLN, " + allergens.found); // 92.0 PLN, [celery, gluten, milk]
}
}package main
import (
"fmt"
"math"
"slices"
)
type Visitor interface {
VisitDish(*Dish)
VisitDrink(*Drink)
VisitCombo(*Combo)
}
type MenuItem interface{ Accept(Visitor) }
type Dish struct {
Name string
Price float64
Allergens []string
}
type Drink struct {
Name string
Price, Litres float64
}
type Combo struct {
Name string
Discount float64
Items []MenuItem
}
// Double dispatch: each item calls the method meant for its own type.
func (d *Dish) Accept(v Visitor) { v.VisitDish(d) }
func (d *Drink) Accept(v Visitor) { v.VisitDrink(d) }
func (c *Combo) Accept(v Visitor) { v.VisitCombo(c) }
// PriceVisitor is a new operation; the menu types stay untouched.
type PriceVisitor struct{ Total float64 }
func (p *PriceVisitor) VisitDish(d *Dish) { p.Total += d.Price }
func (p *PriceVisitor) VisitDrink(d *Drink) { p.Total += d.Price }
func (p *PriceVisitor) VisitCombo(c *Combo) {
inner := &PriceVisitor{}
for _, it := range c.Items {
it.Accept(inner)
}
p.Total += math.Round(inner.Total*(1-c.Discount)*100) / 100
}
type AllergenVisitor struct{ Found []string }
func (a *AllergenVisitor) VisitDish(d *Dish) { a.Found = append(a.Found, d.Allergens...) }
func (a *AllergenVisitor) VisitDrink(*Drink) {}
func (a *AllergenVisitor) VisitCombo(c *Combo) {
for _, it := range c.Items {
it.Accept(a)
}
}
func main() {
menu := []MenuItem{
&Combo{"Lunch set", 0.10, []MenuItem{
&Dish{"Ruskie", 28, []string{"gluten", "milk"}},
&Dish{"Soup of the day", 14, []string{"celery"}},
&Drink{"Kompot", 8, 0.3},
}},
&Dish{"With black pudding", 35, []string{"gluten"}},
&Drink{"Lemonade", 12, 0.5},
}
prices, allergens := &PriceVisitor{}, &AllergenVisitor{}
for _, it := range menu {
it.Accept(prices)
it.Accept(allergens)
}
slices.Sort(allergens.Found)
fmt.Println(prices.Total, slices.Compact(allergens.Found)) // 92 [celery gluten milk]
}from __future__ import annotations
from dataclasses import dataclass
from typing import Protocol
class MenuVisitor(Protocol):
def visit_dish(self, dish: Dish) -> None: ...
def visit_drink(self, drink: Drink) -> None: ...
def visit_combo(self, combo: Combo) -> None: ...
class Visitable:
def accept(self, v: MenuVisitor) -> None:
# Double dispatch by name, like ast.NodeVisitor: Dish -> v.visit_dish(self)
getattr(v, f"visit_{type(self).__name__.lower()}")(self)
@dataclass(frozen=True)
class Dish(Visitable):
name: str
price: float
allergens: tuple[str, ...] = ()
@dataclass(frozen=True)
class Drink(Visitable):
name: str
price: float
litres: float
@dataclass(frozen=True)
class Combo(Visitable):
name: str
discount: float
items: tuple[Dish | Drink | Combo, ...]
class PriceVisitor:
"""A new operation is a new visitor – the menu classes stay untouched."""
def __init__(self) -> None:
self.total = 0.0
def visit_dish(self, dish: Dish) -> None:
self.total += dish.price
def visit_drink(self, drink: Drink) -> None:
self.total += drink.price
def visit_combo(self, combo: Combo) -> None:
inner = PriceVisitor()
for item in combo.items:
item.accept(inner)
self.total += round(inner.total * (1 - combo.discount), 2)
class AllergenVisitor:
def __init__(self) -> None:
self.found: set[str] = set()
def visit_dish(self, dish: Dish) -> None:
self.found.update(dish.allergens)
def visit_drink(self, drink: Drink) -> None:
pass
def visit_combo(self, combo: Combo) -> None:
for item in combo.items:
item.accept(self)
menu = [
Combo("Lunch set", 0.10, (Dish("Ruskie", 28, ("gluten", "milk")),
Dish("Soup of the day", 14, ("celery",)),
Drink("Kompot", 8, 0.3))),
Dish("With black pudding", 35, ("gluten",)),
Drink("Lemonade", 12, 0.5),
]
prices, allergens = PriceVisitor(), AllergenVisitor()
for item in menu:
item.accept(prices)
item.accept(allergens)
print(prices.total, sorted(allergens.found)) # 92.0 ['celery', 'gluten', 'milk']The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- The expression problem: when Visitor pays off
- The modern alternative: pattern matching
- When to use it and when not to
- Related patterns
- In practice
- Test yourself