English

Artykuł · Odwiedzający

Odwiedzający (Visitor): nowe operacje bez zmiany klas

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.

Autor · · 15 min czytania

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. Odwiedzający (ang. Visitor) pozwala dodawać takie operacje jako osobne obiekty, bez dopisywania kolejnych metod do klas dań.

3
typy pozycji w menu – danie, napój, zestaw
2
operacje w przykładzie – cena i raport alergenów
0
zmian w klasach menu – przy dodaniu kolejnej operacji

Problem: klasy, które robią wszystko dla wszystkich

Każda nowa potrzeba kończyła się nową metodą w klasach menu:

menu-before.ts
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 team

Klasa Dish 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.

Rozwiązanie: operacja przychodzi do danych

Odwiedzający odwraca układ. Klasy menu dostają jedną metodę accept(visitor) i nic więcej nie wiedzą o operacjach. Każda operacja to klasa implementująca interfejs MenuVisitor z metodą dla każdego typu pozycji: visitDish, visitDrink, visitCombo. Cała logika liczenia cen trafia do PriceVisitor, cała logika alergenów – do AllergenVisitor.

Diagram: Podwójna dyspozycja: dwa wywołania wybierają właściwy kod
Diagram: Struktura wzorca Odwiedzający
RolaW przykładzieOdpowiedzialność
Odwiedzający (Visitor)MenuVisitormetoda dla każdego typu elementu
Konkretny odwiedzającyPriceVisitor, AllergenVisitorjedna operacja na całej strukturze
ElementMenuItemmetoda accept(visitor)
Konkretny elementDish, Drink, Combow accept woła metodę odwiedzającego dla swojego typu
Struktura obiektówlista pozycji, zestawyzbiór elementów do odwiedzenia

Implementacja w pięciu językach

W C# i Javie metody odwiedzającego to przeciążenia visit(...) – kompilator wybiera właściwe na podstawie statycznego typu this wewnątrz accept. TypeScript, Go i Python nie mają przeciążeń, więc metody mają różne nazwy (visitDish, VisitDish, visit_dish). Zwróć uwagę, że to odwiedzający decydują, jak przejść po zawartości zestawu – PriceVisitor liczy ją osobno, żeby naliczyć rabat.

Odwiedzający – operacje na karcie dań

MenuVisitors.cs
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); }
}
menu-visitors.ts
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' ]
MenuVisitors.java
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]
    }
}
menu.go
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]
}
menu_visitors.py
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']

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Problem wyrażenia: kiedy Odwiedzający się opłaca
  • Nowoczesna alternatywa: dopasowanie wzorców
  • Kiedy stosować, a kiedy nie
  • Powiązania z innymi wzorcami
  • W praktyce
  • Sprawdź się

Załóż darmowe konto · Zaloguj się