Artykuł · Obserwator · Architektura sterowana zdarzeniami
Obserwator (Observer): powiadom wszystkich, nie znając nikogo
Wzorzec Obserwator na przykładzie spiżarni pierogarni: gdy kończy się ser, menu, lista zakupów i alerty reagują same, a magazyn nie wie o ich istnieniu. Subskrypcja, wypisanie, pułapki i kod w pięciu językach.
W pierogarni Haliny ser twarogowy kończy się zawsze w najgorszym momencie. Gdy stan spada do zera, trzeba ukryć ruskie w menu, dopisać ser do listy zakupów i – w weekend – wysłać Halinie SMS. Obserwator (ang. Observer) pozwala, by spiżarnia ogłosiła zmianę, a zainteresowani zareagowali sami, bez wzajemnej znajomości.
- 1 → N
- jeden podmiot, wielu odbiorców – liczba obserwatorów nie jest znana z góry
- 0
- importów odbiorców w podmiocie – spiżarnia nie wie, kto słucha
- 3
- typowe pułapki – wycieki, kolejność i wyjątki w obserwatorach
Problem: spiżarnia, która wie za dużo
Pierwsza wersja magazynu wołała wszystkich zainteresowanych bezpośrednio:
class Pantry {
constructor(
private readonly menu: MenuBoard,
private readonly shopping: ShoppingList,
private readonly sms: SmsGateway,
) {}
use(ingredient: string, amount: number): void {
const current = this.decrease(ingredient, amount);
if (current === 0) this.menu.hideDishesWith(ingredient);
if (current < 3) this.shopping.add(ingredient);
if (current < 3 && isWeekend()) this.sms.send('+48 600 000 000', `Low on ${ingredient}!`);
// next sprint: loyalty app, kitchen display, weekly report...
}
}Klasa Pantry zależy od menu, listy zakupów i bramki SMS. Każdy nowy odbiorca – aplikacja lojalnościowa, ekran w kuchni, cotygodniowy raport – to kolejny parametr konstruktora i kolejny if w metodzie, która miała tylko zmniejszyć stan magazynu. Testy jednostkowe spiżarni wymagają atrap trzech niezwiązanych usług, a awaria bramki SMS potrafi przerwać zdejmowanie składnika ze stanu.
Rozwiązanie: ogłoś zmianę, nie wołaj adresatów
Spiżarnia przestaje wołać konkretne klasy. Zamiast tego udostępnia subskrypcję: każdy zainteresowany rejestruje funkcję lub obiekt z metodą onStockChanged. Gdy stan się zmienia, spiżarnia przechodzi po liście i powiadamia wszystkich – nie wiedząc, czy po drugiej stronie jest menu, SMS czy test jednostkowy.
| Rola | W przykładzie | Odpowiedzialność |
|---|---|---|
| Podmiot (Subject) | Pantry | przechowuje subskrypcje i ogłasza zmiany |
| Obserwator (Observer) | StockListener / typ funkcji | wspólny interfejs reakcji na zmianę |
| Konkretny obserwator | MenuBoard, ShoppingList, SmsAlert | robi coś z powiadomieniem, nie wiedząc o innych |
| Zdarzenie | StockChange | dane zmiany: składnik, poprzedni i bieżący stan |
Implementacja w pięciu językach
W C# wzorzec jest wbudowany w język jako event, w TypeScripcie i Pythonie wystarczy zbiór funkcji, w Javie – lista słuchaczy, a w Go – mapa funkcji chroniona muteksem. W każdym wariancie subskrypcja zwraca sposób na wypisanie się.
Obserwator – stan spiżarni
var pantry = new Pantry();
var menu = new MenuBoard();
pantry.StockChanged += menu.OnStockChanged;
pantry.StockChanged += (_, e) =>
{
if (e.Current < 3) Console.WriteLine($"Shopping list: buy {e.Ingredient}");
};
pantry.Use("cheese", 4); // menu hides dishes, shopping list reacts
pantry.StockChanged -= menu.OnStockChanged; // always unsubscribe long-lived subjects
pantry.Restock("cheese", 10);
public sealed record StockChange(string Ingredient, int Previous, int Current);
public sealed class Pantry
{
private readonly Dictionary<string, int> _stock = new() { ["cheese"] = 4, ["potatoes"] = 20 };
// The subject only knows the delegate type, not the subscribers.
public event EventHandler<StockChange>? StockChanged;
public void Use(string ingredient, int amount) => Set(ingredient, Stock(ingredient) - amount);
public void Restock(string ingredient, int amount) => Set(ingredient, Stock(ingredient) + amount);
private int Stock(string ingredient) => _stock.GetValueOrDefault(ingredient);
private void Set(string ingredient, int current)
{
var previous = Stock(ingredient);
if (previous == current) return;
_stock[ingredient] = current;
StockChanged?.Invoke(this, new StockChange(ingredient, previous, current));
}
}
public sealed class MenuBoard
{
public void OnStockChanged(object? sender, StockChange e)
{
if (e.Current == 0) Console.WriteLine($"Menu: hiding dishes with {e.Ingredient}");
else if (e.Previous == 0) Console.WriteLine($"Menu: dishes with {e.Ingredient} are back");
}
}type StockChange = { ingredient: string; previous: number; current: number };
type Listener = (change: StockChange) => void;
class Pantry {
private readonly stock = new Map<string, number>([['cheese', 4], ['potatoes', 20]]);
private readonly listeners = new Set<Listener>();
/** Returns a function that unsubscribes the listener. */
subscribe(listener: Listener): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
use(ingredient: string, amount: number): void {
this.set(ingredient, (this.stock.get(ingredient) ?? 0) - amount);
}
restock(ingredient: string, amount: number): void {
this.set(ingredient, (this.stock.get(ingredient) ?? 0) + amount);
}
private set(ingredient: string, current: number): void {
const previous = this.stock.get(ingredient) ?? 0;
if (previous === current) return;
this.stock.set(ingredient, current);
// Iterate over a copy, so a listener may unsubscribe while being notified.
for (const listener of [...this.listeners]) listener({ ingredient, previous, current });
}
}
const pantry = new Pantry();
const stopMenu = pantry.subscribe(({ ingredient, previous, current }) => {
if (current === 0) console.log(`Menu: hiding dishes with ${ingredient}`);
else if (previous === 0) console.log(`Menu: dishes with ${ingredient} are back`);
});
pantry.subscribe(({ ingredient, current }) => {
if (current < 3) console.log(`Shopping list: buy ${ingredient}`);
});
pantry.use('cheese', 4); // menu hides dishes, shopping list reacts
stopMenu();
pantry.restock('cheese', 10); // the menu no longer hears about itimport java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
record StockChange(String ingredient, int previous, int current) {}
@FunctionalInterface
interface StockListener {
void onStockChanged(StockChange change);
}
class Pantry {
private final Map<String, Integer> stock = new HashMap<>(Map.of("cheese", 4, "potatoes", 20));
// Safe to iterate while listeners subscribe or unsubscribe.
private final List<StockListener> listeners = new CopyOnWriteArrayList<>();
/** Returns a handle that unsubscribes the listener when closed. */
AutoCloseable subscribe(StockListener listener) {
listeners.add(listener);
return () -> listeners.remove(listener);
}
void use(String ingredient, int amount) { set(ingredient, stock.getOrDefault(ingredient, 0) - amount); }
void restock(String ingredient, int amount) { set(ingredient, stock.getOrDefault(ingredient, 0) + amount); }
private void set(String ingredient, int current) {
int previous = stock.getOrDefault(ingredient, 0);
if (previous == current) return;
stock.put(ingredient, current);
var change = new StockChange(ingredient, previous, current);
listeners.forEach(l -> l.onStockChanged(change));
}
}
public class Kitchen {
public static void main(String[] args) throws Exception {
var pantry = new Pantry();
var menu = pantry.subscribe(c -> {
if (c.current() == 0) System.out.println("Menu: hiding dishes with " + c.ingredient());
else if (c.previous() == 0) System.out.println("Menu: dishes with " + c.ingredient() + " are back");
});
pantry.subscribe(c -> {
if (c.current() < 3) System.out.println("Shopping list: buy " + c.ingredient());
});
pantry.use("cheese", 4);
menu.close(); // unsubscribe
pantry.restock("cheese", 10);
}
}package main
import (
"fmt"
"sync"
)
type StockChange struct {
Ingredient string
Previous, Current int
}
type Pantry struct {
mu sync.Mutex
stock map[string]int
listeners map[*func(StockChange)]struct{} // notification order is not guaranteed
}
func NewPantry() *Pantry {
return &Pantry{stock: map[string]int{"cheese": 4, "potatoes": 20}, listeners: map[*func(StockChange)]struct{}{}}
}
// Subscribe registers a listener and returns a function that removes it.
func (p *Pantry) Subscribe(fn func(StockChange)) (unsubscribe func()) {
key := &fn // a unique key for this subscription
p.mu.Lock()
defer p.mu.Unlock()
p.listeners[key] = struct{}{}
return func() {
p.mu.Lock()
defer p.mu.Unlock()
delete(p.listeners, key)
}
}
func (p *Pantry) Use(ingredient string, amount int) { p.add(ingredient, -amount) }
func (p *Pantry) Restock(ingredient string, amount int) { p.add(ingredient, amount) }
func (p *Pantry) add(ingredient string, delta int) {
p.mu.Lock()
change := StockChange{ingredient, p.stock[ingredient], p.stock[ingredient] + delta}
p.stock[ingredient] = change.Current
fns := make([]func(StockChange), 0, len(p.listeners))
for fn := range p.listeners {
fns = append(fns, *fn)
}
p.mu.Unlock() // notify outside the lock, so listeners may call back into the pantry
for _, fn := range fns {
fn(change)
}
}
func main() {
pantry := NewPantry()
stopMenu := pantry.Subscribe(func(c StockChange) {
if c.Current == 0 {
fmt.Println("Menu: hiding dishes with", c.Ingredient)
}
})
pantry.Subscribe(func(c StockChange) {
if c.Current < 3 {
fmt.Println("Shopping list: buy", c.Ingredient)
}
})
pantry.Use("cheese", 4)
stopMenu()
pantry.Restock("cheese", 10)
}from dataclasses import dataclass
from typing import Callable
@dataclass(frozen=True)
class StockChange:
ingredient: str
previous: int
current: int
Listener = Callable[[StockChange], None]
class Pantry:
def __init__(self) -> None:
self._stock = {"cheese": 4, "potatoes": 20}
self._listeners: list[Listener] = []
def subscribe(self, listener: Listener) -> Callable[[], None]:
"""Registers a listener and returns a function that unsubscribes it."""
self._listeners.append(listener)
return lambda: self._listeners.remove(listener)
def use(self, ingredient: str, amount: int) -> None:
self._set(ingredient, self._stock.get(ingredient, 0) - amount)
def restock(self, ingredient: str, amount: int) -> None:
self._set(ingredient, self._stock.get(ingredient, 0) + amount)
def _set(self, ingredient: str, current: int) -> None:
previous = self._stock.get(ingredient, 0)
if previous == current:
return
self._stock[ingredient] = current
change = StockChange(ingredient, previous, current)
for listener in list(self._listeners): # copy: listeners may unsubscribe
listener(change)
def menu_board(change: StockChange) -> None:
if change.current == 0:
print(f"Menu: hiding dishes with {change.ingredient}")
elif change.previous == 0:
print(f"Menu: dishes with {change.ingredient} are back")
def shopping_list(change: StockChange) -> None:
if change.current < 3:
print(f"Shopping list: buy {change.ingredient}")
pantry = Pantry()
stop_menu = pantry.subscribe(menu_board)
pantry.subscribe(shopping_list)
pantry.use("cheese", 4)
stop_menu()
pantry.restock("cheese", 10)Dalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- Push czy pull?
- Pułapki, o których milczą diagramy
- Krótka historia Obserwatora
- Obserwator a Publish/Subscribe
- Kiedy stosować, a kiedy nie
- Powiązania z innymi wzorcami
- W praktyce
- Sprawdź się
- Ćwiczenie