{"id":"6b08bd3f80884893657cca38","slug":"visitor","title":"Visitor: new operations without changing classes","summary":"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.","servedLang":"en","availableLangs":["pl","en"],"topics":["visitor"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","behavioral","visitor","double-dispatch","pattern-matching"],"level":"advanced","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":16,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:14:07.178Z","updatedAt":"2026-11-27T13:07:35.516Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"violet","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"The Visitor design pattern in C#, TypeScript, Java, Go and Python: double dispatch, operations on an object tree and the modern alternative – pattern matching.","wordCount":3143,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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. "},{"type":"text","text":"Visitor","marks":[{"type":"bold"}]},{"type":"text","text":" lets you add such operations as separate objects, without writing yet more methods into the dish classes."}]},{"type":"callout","attrs":{"variant":"tip","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Every "},{"type":"text","text":"operation","marks":[{"type":"bold"}]},{"type":"text","text":" on the structure is a separate visitor class with a method for each element type."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Elements have a single "},{"type":"text","text":"accept(visitor)","marks":[{"type":"code"}]},{"type":"text","text":" method that calls the right visitor method – this is "},{"type":"text","text":"double dispatch","marks":[{"type":"bold"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A new operation is cheap (a new class); a new "},{"type":"text","text":"element type","marks":[{"type":"bold"}]},{"type":"text","text":" is expensive (every visitor changes)."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"3","label":"menu item types","hint":"dish, drink, set"},{"value":"2","label":"operations in the example","hint":"price and allergen report"},{"value":"0","label":"changes in the menu classes","hint":"when another operation is added"}]}},{"type":"heading","attrs":{"level":2,"id":"the-problem-classes-that-do-everything-for-everyone"},"content":[{"type":"text","text":"The problem: classes that do everything for everyone"}]},{"type":"paragraph","content":[{"type":"text","text":"Every new need ended with a new method in the menu classes:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"menu-before.ts"},"content":[{"type":"text","text":"class Dish {\n  constructor(public name: string, public price: number, public allergens: string[]) {}\n\n  totalPrice(): number { return this.price; }\n  allergenList(): string[] { return this.allergens; }\n  toPrintCard(): string { /* typography for the printed menu */ }\n  toDeliveryAppJson(): object { /* the format required by the delivery app */ }\n  vatReportLine(): string { /* accounting */ }\n}\n// ...and the same five methods in Drink and Combo – each one owned by a different team"}]},{"type":"paragraph","content":[{"type":"text","text":"The "},{"type":"text","text":"Dish","marks":[{"type":"code"}]},{"type":"text","text":" 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."}]},{"type":"heading","attrs":{"level":2,"id":"the-solution-the-operation-comes-to-the-data"},"content":[{"type":"text","text":"The solution: the operation comes to the data"}]},{"type":"paragraph","content":[{"type":"text","text":"Visitor flips the arrangement. Menu classes get "},{"type":"text","text":"one","marks":[{"type":"bold"}]},{"type":"text","text":" method, "},{"type":"text","text":"accept(visitor)","marks":[{"type":"code"}]},{"type":"text","text":", and know nothing else about operations. Each operation is a class implementing the "},{"type":"text","text":"MenuVisitor","marks":[{"type":"code"}]},{"type":"text","text":" interface with a method for every item type: "},{"type":"text","text":"visitDish","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"visitDrink","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"visitCombo","marks":[{"type":"code"}]},{"type":"text","text":". All the pricing logic goes into "},{"type":"text","text":"PriceVisitor","marks":[{"type":"code"}]},{"type":"text","text":", all the allergen logic into "},{"type":"text","text":"AllergenVisitor","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant C as Client\n  participant I as item: MenuItem (set)\n  participant V as PriceVisitor\n  participant D as Dish (Ruskie)\n  C->>I: accept(visitor)\n  Note over I: 1st dispatch – on the element type\n  I->>V: visitCombo(this)\n  Note over V: 2nd dispatch – on the visitor type\n  V->>D: accept(inner)\n  D->>V: visitDish(this)\n  V-->>C: set total with discount","caption":"Double dispatch: two calls pick the right code"}},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  class MenuVisitor {\n    <<interface>>\n    +visitDish(Dish)\n    +visitDrink(Drink)\n    +visitCombo(Combo)\n  }\n  class MenuItem {\n    <<interface>>\n    +accept(MenuVisitor)\n  }\n  MenuItem <|.. Dish\n  MenuItem <|.. Drink\n  MenuItem <|.. Combo\n  Combo o--> MenuItem : items\n  MenuVisitor <|.. PriceVisitor\n  MenuVisitor <|.. AllergenVisitor","caption":"The structure of the Visitor pattern"}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Role"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"In the example"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Responsibility"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Visitor"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"MenuVisitor","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a method for each element type"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Concrete visitor"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"PriceVisitor","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"AllergenVisitor","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"one operation over the whole structure"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Element"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"MenuItem","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the "},{"type":"text","text":"accept(visitor)","marks":[{"type":"code"}]},{"type":"text","text":" method"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Concrete element"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Dish","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Drink","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Combo","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"in "},{"type":"text","text":"accept","marks":[{"type":"code"}]},{"type":"text","text":" calls the visitor method for its own type"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Object structure"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the item list, sets"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the collection of elements to visit"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"implementation-in-five-languages"},"content":[{"type":"text","text":"Implementation in five languages"}]},{"type":"paragraph","content":[{"type":"text","text":"In C# and Java the visitor methods are "},{"type":"text","text":"visit(...)","marks":[{"type":"code"}]},{"type":"text","text":" overloads – the compiler picks the right one based on the static type of "},{"type":"text","text":"this","marks":[{"type":"code"}]},{"type":"text","text":" inside "},{"type":"text","text":"accept","marks":[{"type":"code"}]},{"type":"text","text":". TypeScript, Go and Python have no overloading, so the methods have different names ("},{"type":"text","text":"visitDish","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"VisitDish","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"visit_dish","marks":[{"type":"code"}]},{"type":"text","text":"). Notice that the visitors decide how to walk the contents of a set – "},{"type":"text","text":"PriceVisitor","marks":[{"type":"code"}]},{"type":"text","text":" sums it separately in order to apply the discount."}]},{"type":"codeGroup","attrs":{"title":"Visitor – operations on the menu"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"MenuVisitors.cs"},"content":[{"type":"text","text":"IMenuItem[] menu =\n[\n    new Combo(\"Lunch set\", 0.10m,\n    [\n        new Dish(\"Ruskie\", 28m, [\"gluten\", \"milk\"]),\n        new Dish(\"Soup of the day\", 14m, [\"celery\"]),\n        new Drink(\"Kompot\", 8m, 0.3m),\n    ]),\n    new Dish(\"With black pudding\", 35m, [\"gluten\"]),\n    new Drink(\"Lemonade\", 12m, 0.5m),\n];\n\nvar prices = new PriceVisitor();\nvar allergens = new AllergenVisitor();\nforeach (var item in menu) { item.Accept(prices); item.Accept(allergens); }\nConsole.WriteLine($\"Total: {prices.Total} PLN\");                       // Total: 92.00 PLN\nConsole.WriteLine($\"Allergens: {string.Join(\", \", allergens.Found)}\"); // celery, gluten, milk\n\npublic interface IMenuVisitor\n{\n    void Visit(Dish dish);\n    void Visit(Drink drink);\n    void Visit(Combo combo);\n}\n\npublic interface IMenuItem\n{\n    void Accept(IMenuVisitor visitor);\n}\n\n// Double dispatch: the item's own type picks the right Visit overload.\npublic sealed record Dish(string Name, decimal Price, string[] Allergens) : IMenuItem\n{\n    public void Accept(IMenuVisitor v) => v.Visit(this);\n}\n\npublic sealed record Drink(string Name, decimal Price, decimal Litres) : IMenuItem\n{\n    public void Accept(IMenuVisitor v) => v.Visit(this);\n}\n\npublic sealed record Combo(string Name, decimal Discount, IMenuItem[] Items) : IMenuItem\n{\n    public void Accept(IMenuVisitor v) => v.Visit(this);\n}\n\n// A new operation is a new visitor – the menu classes stay untouched.\npublic sealed class PriceVisitor : IMenuVisitor\n{\n    public decimal Total { get; private set; }\n    public void Visit(Dish dish) => Total += dish.Price;\n    public void Visit(Drink drink) => Total += drink.Price;\n    public void Visit(Combo combo)\n    {\n        var inner = new PriceVisitor();\n        foreach (var item in combo.Items) item.Accept(inner);\n        Total += Math.Round(inner.Total * (1 - combo.Discount), 2);\n    }\n}\n\npublic sealed class AllergenVisitor : IMenuVisitor\n{\n    public SortedSet<string> Found { get; } = [];\n    public void Visit(Dish dish) => Found.UnionWith(dish.Allergens);\n    public void Visit(Drink drink) { }\n    public void Visit(Combo combo) { foreach (var item in combo.Items) item.Accept(this); }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"menu-visitors.ts"},"content":[{"type":"text","text":"interface MenuVisitor {\n  visitDish(dish: Dish): void;\n  visitDrink(drink: Drink): void;\n  visitCombo(combo: Combo): void;\n}\n\ninterface MenuItem {\n  accept(visitor: MenuVisitor): void;\n}\n\n// Double dispatch: each item calls the visitor method meant for its own type.\nclass Dish implements MenuItem {\n  constructor(readonly name: string, readonly price: number, readonly allergens: string[]) {}\n  accept(v: MenuVisitor): void { v.visitDish(this); }\n}\n\nclass Drink implements MenuItem {\n  constructor(readonly name: string, readonly price: number, readonly litres: number) {}\n  accept(v: MenuVisitor): void { v.visitDrink(this); }\n}\n\nclass Combo implements MenuItem {\n  constructor(readonly name: string, readonly discount: number, readonly items: MenuItem[]) {}\n  accept(v: MenuVisitor): void { v.visitCombo(this); }\n}\n\n// A new operation is a new visitor – the menu classes stay untouched.\nclass PriceVisitor implements MenuVisitor {\n  total = 0;\n  visitDish(d: Dish) { this.total += d.price; }\n  visitDrink(d: Drink) { this.total += d.price; }\n  visitCombo(c: Combo) {\n    const inner = new PriceVisitor();\n    c.items.forEach((i) => i.accept(inner));\n    this.total += Math.round(inner.total * (1 - c.discount) * 100) / 100;\n  }\n}\n\nclass AllergenVisitor implements MenuVisitor {\n  readonly found = new Set<string>();\n  visitDish(d: Dish) { d.allergens.forEach((a) => this.found.add(a)); }\n  visitDrink() {}\n  visitCombo(c: Combo) { c.items.forEach((i) => i.accept(this)); }\n}\n\nconst menu: MenuItem[] = [\n  new Combo('Lunch set', 0.1, [\n    new Dish('Ruskie', 28, ['gluten', 'milk']),\n    new Dish('Soup of the day', 14, ['celery']),\n    new Drink('Kompot', 8, 0.3),\n  ]),\n  new Dish('With black pudding', 35, ['gluten']),\n  new Drink('Lemonade', 12, 0.5),\n];\n\nconst prices = new PriceVisitor();\nconst allergens = new AllergenVisitor();\nmenu.forEach((item) => { item.accept(prices); item.accept(allergens); });\nconsole.log(prices.total, [...allergens.found].sort()); // 92 [ 'celery', 'gluten', 'milk' ]"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"MenuVisitors.java"},"content":[{"type":"text","text":"import java.util.List;\nimport java.util.TreeSet;\n\ninterface MenuVisitor {\n    void visit(Dish dish);\n    void visit(Drink drink);\n    void visit(Combo combo);\n}\n\nsealed interface MenuItem permits Dish, Drink, Combo {\n    void accept(MenuVisitor visitor);\n}\n\n// Double dispatch: inside accept() the static type of \"this\" picks the overload.\nrecord Dish(String name, double price, List<String> allergens) implements MenuItem {\n    public void accept(MenuVisitor v) { v.visit(this); }\n}\n\nrecord Drink(String name, double price, double litres) implements MenuItem {\n    public void accept(MenuVisitor v) { v.visit(this); }\n}\n\nrecord Combo(String name, double discount, List<MenuItem> items) implements MenuItem {\n    public void accept(MenuVisitor v) { v.visit(this); }\n}\n\n// A new operation is a new visitor – the menu classes stay untouched.\nclass PriceVisitor implements MenuVisitor {\n    double total;\n    public void visit(Dish d) { total += d.price(); }\n    public void visit(Drink d) { total += d.price(); }\n    public void visit(Combo c) {\n        var inner = new PriceVisitor();\n        c.items().forEach(i -> i.accept(inner));\n        total += Math.round(inner.total * (1 - c.discount()) * 100) / 100.0;\n    }\n}\n\nclass AllergenVisitor implements MenuVisitor {\n    final TreeSet<String> found = new TreeSet<>();\n    public void visit(Dish d) { found.addAll(d.allergens()); }\n    public void visit(Drink d) {}\n    public void visit(Combo c) { c.items().forEach(i -> i.accept(this)); }\n}\n\npublic class MenuVisitors {\n    public static void main(String[] args) {\n        List<MenuItem> menu = List.of(\n            new Combo(\"Lunch set\", 0.10, List.of(\n                new Dish(\"Ruskie\", 28, List.of(\"gluten\", \"milk\")),\n                new Dish(\"Soup of the day\", 14, List.of(\"celery\")),\n                new Drink(\"Kompot\", 8, 0.3))),\n            new Dish(\"With black pudding\", 35, List.of(\"gluten\")),\n            new Drink(\"Lemonade\", 12, 0.5));\n\n        var prices = new PriceVisitor();\n        var allergens = new AllergenVisitor();\n        menu.forEach(i -> { i.accept(prices); i.accept(allergens); });\n        System.out.println(prices.total + \" PLN, \" + allergens.found); // 92.0 PLN, [celery, gluten, milk]\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"menu.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"slices\"\n)\n\ntype Visitor interface {\n\tVisitDish(*Dish)\n\tVisitDrink(*Drink)\n\tVisitCombo(*Combo)\n}\n\ntype MenuItem interface{ Accept(Visitor) }\n\ntype Dish struct {\n\tName      string\n\tPrice     float64\n\tAllergens []string\n}\n\ntype Drink struct {\n\tName          string\n\tPrice, Litres float64\n}\n\ntype Combo struct {\n\tName     string\n\tDiscount float64\n\tItems    []MenuItem\n}\n\n// Double dispatch: each item calls the method meant for its own type.\nfunc (d *Dish) Accept(v Visitor)  { v.VisitDish(d) }\nfunc (d *Drink) Accept(v Visitor) { v.VisitDrink(d) }\nfunc (c *Combo) Accept(v Visitor) { v.VisitCombo(c) }\n\n// PriceVisitor is a new operation; the menu types stay untouched.\ntype PriceVisitor struct{ Total float64 }\n\nfunc (p *PriceVisitor) VisitDish(d *Dish)   { p.Total += d.Price }\nfunc (p *PriceVisitor) VisitDrink(d *Drink) { p.Total += d.Price }\nfunc (p *PriceVisitor) VisitCombo(c *Combo) {\n\tinner := &PriceVisitor{}\n\tfor _, it := range c.Items {\n\t\tit.Accept(inner)\n\t}\n\tp.Total += math.Round(inner.Total*(1-c.Discount)*100) / 100\n}\n\ntype AllergenVisitor struct{ Found []string }\n\nfunc (a *AllergenVisitor) VisitDish(d *Dish) { a.Found = append(a.Found, d.Allergens...) }\nfunc (a *AllergenVisitor) VisitDrink(*Drink) {}\nfunc (a *AllergenVisitor) VisitCombo(c *Combo) {\n\tfor _, it := range c.Items {\n\t\tit.Accept(a)\n\t}\n}\n\nfunc main() {\n\tmenu := []MenuItem{\n\t\t&Combo{\"Lunch set\", 0.10, []MenuItem{\n\t\t\t&Dish{\"Ruskie\", 28, []string{\"gluten\", \"milk\"}},\n\t\t\t&Dish{\"Soup of the day\", 14, []string{\"celery\"}},\n\t\t\t&Drink{\"Kompot\", 8, 0.3},\n\t\t}},\n\t\t&Dish{\"With black pudding\", 35, []string{\"gluten\"}},\n\t\t&Drink{\"Lemonade\", 12, 0.5},\n\t}\n\tprices, allergens := &PriceVisitor{}, &AllergenVisitor{}\n\tfor _, it := range menu {\n\t\tit.Accept(prices)\n\t\tit.Accept(allergens)\n\t}\n\tslices.Sort(allergens.Found)\n\tfmt.Println(prices.Total, slices.Compact(allergens.Found)) // 92 [celery gluten milk]\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"menu_visitors.py"},"content":[{"type":"text","text":"from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Protocol\n\n\nclass MenuVisitor(Protocol):\n    def visit_dish(self, dish: Dish) -> None: ...\n    def visit_drink(self, drink: Drink) -> None: ...\n    def visit_combo(self, combo: Combo) -> None: ...\n\n\nclass Visitable:\n    def accept(self, v: MenuVisitor) -> None:\n        # Double dispatch by name, like ast.NodeVisitor: Dish -> v.visit_dish(self)\n        getattr(v, f\"visit_{type(self).__name__.lower()}\")(self)\n\n\n@dataclass(frozen=True)\nclass Dish(Visitable):\n    name: str\n    price: float\n    allergens: tuple[str, ...] = ()\n\n\n@dataclass(frozen=True)\nclass Drink(Visitable):\n    name: str\n    price: float\n    litres: float\n\n\n@dataclass(frozen=True)\nclass Combo(Visitable):\n    name: str\n    discount: float\n    items: tuple[Dish | Drink | Combo, ...]\n\n\nclass PriceVisitor:\n    \"\"\"A new operation is a new visitor – the menu classes stay untouched.\"\"\"\n\n    def __init__(self) -> None:\n        self.total = 0.0\n\n    def visit_dish(self, dish: Dish) -> None:\n        self.total += dish.price\n\n    def visit_drink(self, drink: Drink) -> None:\n        self.total += drink.price\n\n    def visit_combo(self, combo: Combo) -> None:\n        inner = PriceVisitor()\n        for item in combo.items:\n            item.accept(inner)\n        self.total += round(inner.total * (1 - combo.discount), 2)\n\n\nclass AllergenVisitor:\n    def __init__(self) -> None:\n        self.found: set[str] = set()\n\n    def visit_dish(self, dish: Dish) -> None:\n        self.found.update(dish.allergens)\n\n    def visit_drink(self, drink: Drink) -> None:\n        pass\n\n    def visit_combo(self, combo: Combo) -> None:\n        for item in combo.items:\n            item.accept(self)\n\n\nmenu = [\n    Combo(\"Lunch set\", 0.10, (Dish(\"Ruskie\", 28, (\"gluten\", \"milk\")),\n                              Dish(\"Soup of the day\", 14, (\"celery\",)),\n                              Drink(\"Kompot\", 8, 0.3))),\n    Dish(\"With black pudding\", 35, (\"gluten\",)),\n    Drink(\"Lemonade\", 12, 0.5),\n]\nprices, allergens = PriceVisitor(), AllergenVisitor()\nfor item in menu:\n    item.accept(prices)\n    item.accept(allergens)\nprint(prices.total, sorted(allergens.found))  # 92.0 ['celery', 'gluten', 'milk']"}]}]}]},"toc":[{"id":"the-problem-classes-that-do-everything-for-everyone","text":"The problem: classes that do everything for everyone","level":2,"locked":false},{"id":"the-solution-the-operation-comes-to-the-data","text":"The solution: the operation comes to the data","level":2,"locked":false},{"id":"implementation-in-five-languages","text":"Implementation in five languages","level":2,"locked":false},{"id":"the-expression-problem-when-visitor-pays-off","text":"The expression problem: when Visitor pays off","level":2,"locked":true},{"id":"the-modern-alternative-pattern-matching","text":"The modern alternative: pattern matching","level":2,"locked":true},{"id":"when-to-use-it-and-when-not-to","text":"When to use it and when not to","level":2,"locked":true},{"id":"related-patterns","text":"Related patterns","level":2,"locked":true},{"id":"in-practice","text":"In practice","level":2,"locked":true},{"id":"test-yourself","text":"Test yourself","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":38,"visibleBlocks":15,"resources":[{"id":"6b0857c63c96f2d34d0b48b7","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=45MgUX_ih0s","embedUrl":"https://www.youtube-nocookie.com/embed/45MgUX_ih0s","title":"The Visitor Pattern in Python (And Better Alternatives)","description":"💡 Learn how to design great software in 7 steps: https://arjan.codes/designguide. The Visitor pattern has a reputation for being complicated, but the problem it solves is actually quite simple: what happens when you keep adding new operations to the same set of objects? In this video, I use a…","author":"ArjanCodes","thumbnailUrl":"https://i.ytimg.com/vi/45MgUX_ih0s/hqdefault.jpg","durationSec":null,"lang":"en","topics":["visitor"],"techs":["python"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2026-10-23T15:00:28.000Z","popularity":70,"verifiedAt":"2026-11-26T10:54:42.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857bf3c96f2d34d0b42d3","type":"article","provider":"web","url":"https://refactoring.guru/pl/design-patterns/visitor","embedUrl":null,"title":"Odwiedzający / Visitor","description":"Odwiedzający to behawioralny wzorzec projektowy pozwalający oddzielić algorytmy od obiektów na których pracują.","author":"Refactoring.Guru","thumbnailUrl":"https://refactoring.guru/pl/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868","durationSec":null,"lang":"pl","topics":["visitor"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":60,"verifiedAt":"2026-11-26T11:26:14.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857b53c96f2d34d0b3977","type":"article","provider":"web","url":"https://www.lihaoyi.com/post/ZeroOverheadTreeProcessingwiththeVisitorPattern.html?a=1","embedUrl":null,"title":"Zero-Overhead Tree Processing with the Visitor Pattern","description":"","author":"lihaoyi.com","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":["visitor"],"techs":["general"],"tags":["design-patterns","hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2018-05-27T07:07:37.000Z","popularity":67,"verifiedAt":"2026-11-26T11:07:40.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:52.228Z","updatedAt":"2026-11-26T16:00:52.228Z"},{"id":"6b0857b53c96f2d34d0b39ba","type":"article","provider":"web","url":"https://www.haskellforall.com/2021/01/the-visitor-pattern-is-essentially-same.html","embedUrl":null,"title":"The visitor pattern is essentially the same thing as Church encoding","description":"The functional programming analog of an object-oriented design pattern","author":"haskellforall.com","thumbnailUrl":"https://haskellforall.com/2021/01/the-visitor-pattern-is-essentially-same/opengraph-image?133960dfd41055ac","durationSec":null,"lang":"en","topics":["visitor"],"techs":["general"],"tags":["design-patterns","functional-programming","hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2021-02-04T09:45:48.000Z","popularity":65,"verifiedAt":"2026-11-26T11:07:40.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:52.228Z","updatedAt":"2026-11-26T16:00:52.228Z"}],"challenges":[{"id":"6b093dc291bd8fbaf2a0c8dc","slug":"pricing-formula-visitor","title":"Pricing formula visitor","summary":"A pricing formula tree and three operations on it – evaluation, printing and simplification – as visitors. A new operation leaves the node classes untouched.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"hard","topics":["visitor"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["visitor","double-dispatch","expression-tree","composite","behavioral"],"languages":["typescript","javascript","python","csharp","java","go"],"questionCount":null,"xp":40,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:26.391Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"gof-behavioral","title":"GoF behavioral patterns","items":[{"slug":"strategy","title":"Strategy: interchangeable algorithms instead of an if-else ladder","current":false},{"slug":"observer","title":"Observer: notify everyone without knowing anyone","current":false},{"slug":"command","title":"Command: a request wrapped in an object","current":false},{"slug":"state","title":"State: an object that changes behaviour with its life stage","current":false},{"slug":"template-method","title":"Template Method: a fixed recipe, interchangeable ingredients","current":false},{"slug":"iterator","title":"Iterator: walking a collection without looking inside","current":false},{"slug":"chain-of-responsibility","title":"Chain of Responsibility: pass it on until someone takes care of it","current":false},{"slug":"mediator","title":"Mediator: components talk through a coordinator","current":false},{"slug":"memento","title":"Memento: a state snapshot without breaking encapsulation","current":false},{"slug":"visitor","title":"Visitor: new operations without changing classes","current":true}]}],"prev":{"slug":"memento","title":"Memento: a state snapshot without breaking encapsulation"},"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}