{"id":"6b08bd3f80884893657cca38","slug":"visitor","title":"Odwiedzający (Visitor): nowe operacje bez zmiany klas","summary":"Wzorzec Odwiedzający na przykładzie karty dań: dania, napoje i zestawy pozostają nietknięte, a cena, raport alergenów czy eksport to osobne obiekty odwiedzające. Podwójna dyspozycja, porównanie z dopasowaniem wzorców i kod w pięciu językach.","servedLang":"pl","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":15,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:14:07.178Z","updatedAt":"2026-11-27T10:04:58.132Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"violet","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"Wzorzec Odwiedzający (Visitor) w C#, TypeScript, Java, Go i Python: podwójna dyspozycja, operacje na drzewie obiektów i alternatywa – dopasowanie wzorców.","wordCount":2961,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Karta dań pierogarni Haliny to drzewo: dania, napoje i zestawy, które zawierają kolejne pozycje. Na tej samej strukturze pracuje kilka zespołów: księgowość liczy ceny, sanepid chce raportu alergenów, aplikacja dostawcza – eksportu w swoim formacie. "},{"type":"text","text":"Odwiedzający","marks":[{"type":"bold"}]},{"type":"text","text":" (ang. "},{"type":"text","text":"Visitor","marks":[{"type":"italic"}]},{"type":"text","text":") pozwala dodawać takie operacje jako osobne obiekty, bez dopisywania kolejnych metod do klas dań."}]},{"type":"callout","attrs":{"variant":"tip","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Każda "},{"type":"text","text":"operacja","marks":[{"type":"bold"}]},{"type":"text","text":" na strukturze to osobna klasa-odwiedzający z metodą dla każdego typu elementu."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Elementy mają jedną metodę "},{"type":"text","text":"accept(visitor)","marks":[{"type":"code"}]},{"type":"text","text":", która woła właściwą metodę odwiedzającego – to "},{"type":"text","text":"podwójna dyspozycja","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"double dispatch","marks":[{"type":"italic"}]},{"type":"text","text":")."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Nowa operacja jest tania (nowa klasa), nowy "},{"type":"text","text":"typ elementu","marks":[{"type":"bold"}]},{"type":"text","text":" – drogi (zmiana wszystkich odwiedzających)."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"3","label":"typy pozycji w menu","hint":"danie, napój, zestaw"},{"value":"2","label":"operacje w przykładzie","hint":"cena i raport alergenów"},{"value":"0","label":"zmian w klasach menu","hint":"przy dodaniu kolejnej operacji"}]}},{"type":"heading","attrs":{"level":2,"id":"problem-klasy-ktore-robia-wszystko-dla-wszystkich"},"content":[{"type":"text","text":"Problem: klasy, które robią wszystko dla wszystkich"}]},{"type":"paragraph","content":[{"type":"text","text":"Każda nowa potrzeba kończyła się nową metodą w klasach menu:"}]},{"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":"Klasa "},{"type":"text","text":"Dish","marks":[{"type":"code"}]},{"type":"text","text":" zna typografię drukowanej karty, format aplikacji dostawczej i zasady księgowe. Każdy zespół modyfikuje te same trzy pliki, a zmiana eksportu wymaga ponownego testowania cen. Logika jednej operacji – np. raportu VAT – jest rozsmarowana po trzech klasach, więc trudno ją przeczytać w całości."}]},{"type":"heading","attrs":{"level":2,"id":"rozwiazanie-operacja-przychodzi-do-danych"},"content":[{"type":"text","text":"Rozwiązanie: operacja przychodzi do danych"}]},{"type":"paragraph","content":[{"type":"text","text":"Odwiedzający odwraca układ. Klasy menu dostają "},{"type":"text","text":"jedną","marks":[{"type":"bold"}]},{"type":"text","text":" metodę "},{"type":"text","text":"accept(visitor)","marks":[{"type":"code"}]},{"type":"text","text":" i nic więcej nie wiedzą o operacjach. Każda operacja to klasa implementująca interfejs "},{"type":"text","text":"MenuVisitor","marks":[{"type":"code"}]},{"type":"text","text":" z metodą dla każdego typu pozycji: "},{"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":". Cała logika liczenia cen trafia do "},{"type":"text","text":"PriceVisitor","marks":[{"type":"code"}]},{"type":"text","text":", cała logika alergenów – do "},{"type":"text","text":"AllergenVisitor","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant C as Klient\n  participant I as item: MenuItem (zestaw)\n  participant V as PriceVisitor\n  participant D as Dish (Ruskie)\n  C->>I: accept(visitor)\n  Note over I: 1. dyspozycja – po typie elementu\n  I->>V: visitCombo(this)\n  Note over V: 2. dyspozycja – po typie odwiedzającego\n  V->>D: accept(inner)\n  D->>V: visitDish(this)\n  V-->>C: suma zestawu z rabatem","caption":"Podwójna dyspozycja: dwa wywołania wybierają właściwy kod"}},{"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":"Struktura wzorca Odwiedzający"}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Rola"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"W przykładzie"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Odpowiedzialność"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Odwiedzający ("},{"type":"text","text":"Visitor","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"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":"metoda dla każdego typu elementu"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Konkretny odwiedzający"}]}]},{"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":"jedna operacja na całej strukturze"}]}]}]},{"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":"metoda "},{"type":"text","text":"accept(visitor)","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Konkretny 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":"w "},{"type":"text","text":"accept","marks":[{"type":"code"}]},{"type":"text","text":" woła metodę odwiedzającego dla swojego typu"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Struktura obiektów"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"lista pozycji, zestawy"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zbiór elementów do odwiedzenia"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"implementacja-w-pieciu-jezykach"},"content":[{"type":"text","text":"Implementacja w pięciu językach"}]},{"type":"paragraph","content":[{"type":"text","text":"W C# i Javie metody odwiedzającego to przeciążenia "},{"type":"text","text":"visit(...)","marks":[{"type":"code"}]},{"type":"text","text":" – kompilator wybiera właściwe na podstawie statycznego typu "},{"type":"text","text":"this","marks":[{"type":"code"}]},{"type":"text","text":" wewnątrz "},{"type":"text","text":"accept","marks":[{"type":"code"}]},{"type":"text","text":". TypeScript, Go i Python nie mają przeciążeń, więc metody mają różne nazwy ("},{"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":"). Zwróć uwagę, że to odwiedzający decydują, jak przejść po zawartości zestawu – "},{"type":"text","text":"PriceVisitor","marks":[{"type":"code"}]},{"type":"text","text":" liczy ją osobno, żeby naliczyć rabat."}]},{"type":"codeGroup","attrs":{"title":"Odwiedzający – operacje na karcie dań"},"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":"problem-klasy-ktore-robia-wszystko-dla-wszystkich","text":"Problem: klasy, które robią wszystko dla wszystkich","level":2,"locked":false},{"id":"rozwiazanie-operacja-przychodzi-do-danych","text":"Rozwiązanie: operacja przychodzi do danych","level":2,"locked":false},{"id":"implementacja-w-pieciu-jezykach","text":"Implementacja w pięciu językach","level":2,"locked":false},{"id":"problem-wyrazenia-kiedy-odwiedzajacy-sie-oplaca","text":"Problem wyrażenia: kiedy Odwiedzający się opłaca","level":2,"locked":true},{"id":"nowoczesna-alternatywa-dopasowanie-wzorcow","text":"Nowoczesna alternatywa: dopasowanie wzorców","level":2,"locked":true},{"id":"kiedy-stosowac-a-kiedy-nie","text":"Kiedy stosować, a kiedy nie","level":2,"locked":true},{"id":"powiazania-z-innymi-wzorcami","text":"Powiązania z innymi wzorcami","level":2,"locked":true},{"id":"w-praktyce","text":"W praktyce","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","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":"Odwiedzający dla formuł cenowych","summary":"Drzewo formuły cenowej i trzy operacje na nim – obliczanie, wypisywanie i upraszczanie – jako odwiedzający. Nowa operacja nie zmienia klas węzłów.","servedLang":"pl","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":"Wzorce behawioralne GoF","items":[{"slug":"strategy","title":"Strategia (Strategy): wymienne algorytmy zamiast drabinki if-ów","current":false},{"slug":"observer","title":"Obserwator (Observer): powiadom wszystkich, nie znając nikogo","current":false},{"slug":"command","title":"Polecenie (Command): żądanie zamknięte w obiekcie","current":false},{"slug":"state","title":"Stan (State): obiekt, który zmienia zachowanie razem z etapem życia","current":false},{"slug":"template-method","title":"Metoda szablonowa (Template Method): stały przepis, wymienne składniki","current":false},{"slug":"iterator","title":"Iterator: przechodzenie po kolekcji bez zaglądania do środka","current":false},{"slug":"chain-of-responsibility","title":"Łańcuch zobowiązań (Chain of Responsibility): podaj dalej, aż ktoś się zajmie","current":false},{"slug":"mediator","title":"Mediator: komponenty rozmawiają przez koordynatora","current":false},{"slug":"memento","title":"Pamiątka (Memento): migawka stanu bez łamania hermetyzacji","current":false},{"slug":"visitor","title":"Odwiedzający (Visitor): nowe operacje bez zmiany klas","current":true}]}],"prev":{"slug":"memento","title":"Pamiątka (Memento): migawka stanu bez łamania hermetyzacji"},"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":"Autorytet","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":38}]}}