{"id":"6b08bd3c80884893657cc9dd","slug":"observer","title":"Obserwator (Observer): powiadom wszystkich, nie znając nikogo","summary":"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.","servedLang":"pl","availableLangs":["pl","en"],"topics":["observer","event-driven-architecture"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","behavioral","observer","events","pub-sub"],"level":"beginner","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":12,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:14:04.022Z","updatedAt":"2026-11-27T10:04:59.484Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"violet","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"Wzorzec projektowy Obserwator (Observer) w C#, TypeScript, Java, Go i Python: subskrypcja i wypisanie, push vs pull, wycieki pamięci, różnica względem Pub/Sub.","wordCount":2239,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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. "},{"type":"text","text":"Obserwator","marks":[{"type":"bold"}]},{"type":"text","text":" (ang. "},{"type":"text","text":"Observer","marks":[{"type":"italic"}]},{"type":"text","text":") pozwala, by spiżarnia ogłosiła zmianę, a zainteresowani zareagowali sami, bez wzajemnej znajomości."}]},{"type":"callout","attrs":{"variant":"tip","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Podmiot","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"subject","marks":[{"type":"italic"}]},{"type":"text","text":") utrzymuje listę "},{"type":"text","text":"obserwatorów","marks":[{"type":"bold"}]},{"type":"text","text":" i powiadamia ich o zmianie swojego stanu."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Obserwatorzy "},{"type":"text","text":"zapisują się i wypisują","marks":[{"type":"bold"}]},{"type":"text","text":" w czasie działania; podmiot zna tylko ich wspólny interfejs."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Relacja jeden-do-wielu bez sztywnych zależności: nowy odbiorca nie wymaga zmian w podmiocie."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"1 → N","label":"jeden podmiot, wielu odbiorców","hint":"liczba obserwatorów nie jest znana z góry"},{"value":"0","label":"importów odbiorców w podmiocie","hint":"spiżarnia nie wie, kto słucha"},{"value":"3","label":"typowe pułapki","hint":"wycieki, kolejność i wyjątki w obserwatorach"}]}},{"type":"heading","attrs":{"level":2,"id":"problem-spizarnia-ktora-wie-za-duzo"},"content":[{"type":"text","text":"Problem: spiżarnia, która wie za dużo"}]},{"type":"paragraph","content":[{"type":"text","text":"Pierwsza wersja magazynu wołała wszystkich zainteresowanych bezpośrednio:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"pantry-before.ts"},"content":[{"type":"text","text":"class Pantry {\n  constructor(\n    private readonly menu: MenuBoard,\n    private readonly shopping: ShoppingList,\n    private readonly sms: SmsGateway,\n  ) {}\n\n  use(ingredient: string, amount: number): void {\n    const current = this.decrease(ingredient, amount);\n    if (current === 0) this.menu.hideDishesWith(ingredient);\n    if (current < 3) this.shopping.add(ingredient);\n    if (current < 3 && isWeekend()) this.sms.send('+48 600 000 000', `Low on ${ingredient}!`);\n    // next sprint: loyalty app, kitchen display, weekly report...\n  }\n}"}]},{"type":"paragraph","content":[{"type":"text","text":"Klasa "},{"type":"text","text":"Pantry","marks":[{"type":"code"}]},{"type":"text","text":" 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 "},{"type":"text","text":"if","marks":[{"type":"code"}]},{"type":"text","text":" 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."}]},{"type":"heading","attrs":{"level":2,"id":"rozwiazanie-oglos-zmiane-nie-wolaj-adresatow"},"content":[{"type":"text","text":"Rozwiązanie: ogłoś zmianę, nie wołaj adresatów"}]},{"type":"paragraph","content":[{"type":"text","text":"Spiżarnia przestaje wołać konkretne klasy. Zamiast tego udostępnia "},{"type":"text","text":"subskrypcję","marks":[{"type":"bold"}]},{"type":"text","text":": każdy zainteresowany rejestruje funkcję lub obiekt z metodą "},{"type":"text","text":"onStockChanged","marks":[{"type":"code"}]},{"type":"text","text":". 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."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant K as Kuchnia\n  participant P as Pantry (podmiot)\n  participant M as MenuBoard\n  participant S as ShoppingList\n  participant A as SmsAlert\n  M->>P: subscribe()\n  S->>P: subscribe()\n  A->>P: subscribe()\n  K->>P: use(\"cheese\", 4)\n  Note over P: ser: 4 → 0\n  P->>M: onStockChanged(cheese, 4, 0)\n  P->>S: onStockChanged(cheese, 4, 0)\n  P->>A: onStockChanged(cheese, 4, 0)\n  M->>P: unsubscribe()","caption":"Jedna zmiana stanu, trzech odbiorców"}},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  direction LR\n  class Pantry {\n    -listeners: List~StockListener~\n    +subscribe(listener) Unsubscribe\n    +use(ingredient, amount)\n    +restock(ingredient, amount)\n  }\n  class StockListener {\n    <<interface>>\n    +onStockChanged(change)\n  }\n  Pantry o--> StockListener : powiadamia\n  StockListener <|.. MenuBoard\n  StockListener <|.. ShoppingList\n  StockListener <|.. SmsAlert","caption":"Struktura wzorca Obserwator"}},{"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":"Podmiot ("},{"type":"text","text":"Subject","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Pantry","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"przechowuje subskrypcje i ogłasza zmiany"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Obserwator ("},{"type":"text","text":"Observer","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"StockListener","marks":[{"type":"code"}]},{"type":"text","text":" / typ funkcji"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"wspólny interfejs reakcji na zmianę"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Konkretny obserwator"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"MenuBoard","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"ShoppingList","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"SmsAlert","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"robi coś z powiadomieniem, nie wiedząc o innych"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Zdarzenie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"StockChange","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dane zmiany: składnik, poprzedni i bieżący stan"}]}]}]}]},{"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# wzorzec jest wbudowany w język jako "},{"type":"text","text":"event","marks":[{"type":"code"}]},{"type":"text","text":", 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ę."}]},{"type":"codeGroup","attrs":{"title":"Obserwator – stan spiżarni"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"Pantry.cs"},"content":[{"type":"text","text":"var pantry = new Pantry();\nvar menu = new MenuBoard();\npantry.StockChanged += menu.OnStockChanged;\npantry.StockChanged += (_, e) =>\n{\n    if (e.Current < 3) Console.WriteLine($\"Shopping list: buy {e.Ingredient}\");\n};\n\npantry.Use(\"cheese\", 4);                    // menu hides dishes, shopping list reacts\npantry.StockChanged -= menu.OnStockChanged; // always unsubscribe long-lived subjects\npantry.Restock(\"cheese\", 10);\n\npublic sealed record StockChange(string Ingredient, int Previous, int Current);\n\npublic sealed class Pantry\n{\n    private readonly Dictionary<string, int> _stock = new() { [\"cheese\"] = 4, [\"potatoes\"] = 20 };\n\n    // The subject only knows the delegate type, not the subscribers.\n    public event EventHandler<StockChange>? StockChanged;\n\n    public void Use(string ingredient, int amount) => Set(ingredient, Stock(ingredient) - amount);\n    public void Restock(string ingredient, int amount) => Set(ingredient, Stock(ingredient) + amount);\n\n    private int Stock(string ingredient) => _stock.GetValueOrDefault(ingredient);\n\n    private void Set(string ingredient, int current)\n    {\n        var previous = Stock(ingredient);\n        if (previous == current) return;\n        _stock[ingredient] = current;\n        StockChanged?.Invoke(this, new StockChange(ingredient, previous, current));\n    }\n}\n\npublic sealed class MenuBoard\n{\n    public void OnStockChanged(object? sender, StockChange e)\n    {\n        if (e.Current == 0) Console.WriteLine($\"Menu: hiding dishes with {e.Ingredient}\");\n        else if (e.Previous == 0) Console.WriteLine($\"Menu: dishes with {e.Ingredient} are back\");\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"pantry.ts"},"content":[{"type":"text","text":"type StockChange = { ingredient: string; previous: number; current: number };\ntype Listener = (change: StockChange) => void;\n\nclass Pantry {\n  private readonly stock = new Map<string, number>([['cheese', 4], ['potatoes', 20]]);\n  private readonly listeners = new Set<Listener>();\n\n  /** Returns a function that unsubscribes the listener. */\n  subscribe(listener: Listener): () => void {\n    this.listeners.add(listener);\n    return () => this.listeners.delete(listener);\n  }\n\n  use(ingredient: string, amount: number): void {\n    this.set(ingredient, (this.stock.get(ingredient) ?? 0) - amount);\n  }\n\n  restock(ingredient: string, amount: number): void {\n    this.set(ingredient, (this.stock.get(ingredient) ?? 0) + amount);\n  }\n\n  private set(ingredient: string, current: number): void {\n    const previous = this.stock.get(ingredient) ?? 0;\n    if (previous === current) return;\n    this.stock.set(ingredient, current);\n    // Iterate over a copy, so a listener may unsubscribe while being notified.\n    for (const listener of [...this.listeners]) listener({ ingredient, previous, current });\n  }\n}\n\nconst pantry = new Pantry();\nconst stopMenu = pantry.subscribe(({ ingredient, previous, current }) => {\n  if (current === 0) console.log(`Menu: hiding dishes with ${ingredient}`);\n  else if (previous === 0) console.log(`Menu: dishes with ${ingredient} are back`);\n});\npantry.subscribe(({ ingredient, current }) => {\n  if (current < 3) console.log(`Shopping list: buy ${ingredient}`);\n});\n\npantry.use('cheese', 4); // menu hides dishes, shopping list reacts\nstopMenu();\npantry.restock('cheese', 10); // the menu no longer hears about it"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Kitchen.java"},"content":[{"type":"text","text":"import java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.CopyOnWriteArrayList;\n\nrecord StockChange(String ingredient, int previous, int current) {}\n\n@FunctionalInterface\ninterface StockListener {\n    void onStockChanged(StockChange change);\n}\n\nclass Pantry {\n    private final Map<String, Integer> stock = new HashMap<>(Map.of(\"cheese\", 4, \"potatoes\", 20));\n    // Safe to iterate while listeners subscribe or unsubscribe.\n    private final List<StockListener> listeners = new CopyOnWriteArrayList<>();\n\n    /** Returns a handle that unsubscribes the listener when closed. */\n    AutoCloseable subscribe(StockListener listener) {\n        listeners.add(listener);\n        return () -> listeners.remove(listener);\n    }\n\n    void use(String ingredient, int amount) { set(ingredient, stock.getOrDefault(ingredient, 0) - amount); }\n\n    void restock(String ingredient, int amount) { set(ingredient, stock.getOrDefault(ingredient, 0) + amount); }\n\n    private void set(String ingredient, int current) {\n        int previous = stock.getOrDefault(ingredient, 0);\n        if (previous == current) return;\n        stock.put(ingredient, current);\n        var change = new StockChange(ingredient, previous, current);\n        listeners.forEach(l -> l.onStockChanged(change));\n    }\n}\n\npublic class Kitchen {\n    public static void main(String[] args) throws Exception {\n        var pantry = new Pantry();\n        var menu = pantry.subscribe(c -> {\n            if (c.current() == 0) System.out.println(\"Menu: hiding dishes with \" + c.ingredient());\n            else if (c.previous() == 0) System.out.println(\"Menu: dishes with \" + c.ingredient() + \" are back\");\n        });\n        pantry.subscribe(c -> {\n            if (c.current() < 3) System.out.println(\"Shopping list: buy \" + c.ingredient());\n        });\n        pantry.use(\"cheese\", 4);\n        menu.close(); // unsubscribe\n        pantry.restock(\"cheese\", 10);\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"pantry.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype StockChange struct {\n\tIngredient        string\n\tPrevious, Current int\n}\n\ntype Pantry struct {\n\tmu        sync.Mutex\n\tstock     map[string]int\n\tlisteners map[*func(StockChange)]struct{} // notification order is not guaranteed\n}\n\nfunc NewPantry() *Pantry {\n\treturn &Pantry{stock: map[string]int{\"cheese\": 4, \"potatoes\": 20}, listeners: map[*func(StockChange)]struct{}{}}\n}\n\n// Subscribe registers a listener and returns a function that removes it.\nfunc (p *Pantry) Subscribe(fn func(StockChange)) (unsubscribe func()) {\n\tkey := &fn // a unique key for this subscription\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tp.listeners[key] = struct{}{}\n\treturn func() {\n\t\tp.mu.Lock()\n\t\tdefer p.mu.Unlock()\n\t\tdelete(p.listeners, key)\n\t}\n}\n\nfunc (p *Pantry) Use(ingredient string, amount int) { p.add(ingredient, -amount) }\n\nfunc (p *Pantry) Restock(ingredient string, amount int) { p.add(ingredient, amount) }\n\nfunc (p *Pantry) add(ingredient string, delta int) {\n\tp.mu.Lock()\n\tchange := StockChange{ingredient, p.stock[ingredient], p.stock[ingredient] + delta}\n\tp.stock[ingredient] = change.Current\n\tfns := make([]func(StockChange), 0, len(p.listeners))\n\tfor fn := range p.listeners {\n\t\tfns = append(fns, *fn)\n\t}\n\tp.mu.Unlock() // notify outside the lock, so listeners may call back into the pantry\n\tfor _, fn := range fns {\n\t\tfn(change)\n\t}\n}\n\nfunc main() {\n\tpantry := NewPantry()\n\tstopMenu := pantry.Subscribe(func(c StockChange) {\n\t\tif c.Current == 0 {\n\t\t\tfmt.Println(\"Menu: hiding dishes with\", c.Ingredient)\n\t\t}\n\t})\n\tpantry.Subscribe(func(c StockChange) {\n\t\tif c.Current < 3 {\n\t\t\tfmt.Println(\"Shopping list: buy\", c.Ingredient)\n\t\t}\n\t})\n\tpantry.Use(\"cheese\", 4)\n\tstopMenu()\n\tpantry.Restock(\"cheese\", 10)\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"pantry.py"},"content":[{"type":"text","text":"from dataclasses import dataclass\nfrom typing import Callable\n\n\n@dataclass(frozen=True)\nclass StockChange:\n    ingredient: str\n    previous: int\n    current: int\n\n\nListener = Callable[[StockChange], None]\n\n\nclass Pantry:\n    def __init__(self) -> None:\n        self._stock = {\"cheese\": 4, \"potatoes\": 20}\n        self._listeners: list[Listener] = []\n\n    def subscribe(self, listener: Listener) -> Callable[[], None]:\n        \"\"\"Registers a listener and returns a function that unsubscribes it.\"\"\"\n        self._listeners.append(listener)\n        return lambda: self._listeners.remove(listener)\n\n    def use(self, ingredient: str, amount: int) -> None:\n        self._set(ingredient, self._stock.get(ingredient, 0) - amount)\n\n    def restock(self, ingredient: str, amount: int) -> None:\n        self._set(ingredient, self._stock.get(ingredient, 0) + amount)\n\n    def _set(self, ingredient: str, current: int) -> None:\n        previous = self._stock.get(ingredient, 0)\n        if previous == current:\n            return\n        self._stock[ingredient] = current\n        change = StockChange(ingredient, previous, current)\n        for listener in list(self._listeners):  # copy: listeners may unsubscribe\n            listener(change)\n\n\ndef menu_board(change: StockChange) -> None:\n    if change.current == 0:\n        print(f\"Menu: hiding dishes with {change.ingredient}\")\n    elif change.previous == 0:\n        print(f\"Menu: dishes with {change.ingredient} are back\")\n\n\ndef shopping_list(change: StockChange) -> None:\n    if change.current < 3:\n        print(f\"Shopping list: buy {change.ingredient}\")\n\n\npantry = Pantry()\nstop_menu = pantry.subscribe(menu_board)\npantry.subscribe(shopping_list)\npantry.use(\"cheese\", 4)\nstop_menu()\npantry.restock(\"cheese\", 10)"}]}]}]},"toc":[{"id":"problem-spizarnia-ktora-wie-za-duzo","text":"Problem: spiżarnia, która wie za dużo","level":2,"locked":false},{"id":"rozwiazanie-oglos-zmiane-nie-wolaj-adresatow","text":"Rozwiązanie: ogłoś zmianę, nie wołaj adresatów","level":2,"locked":false},{"id":"implementacja-w-pieciu-jezykach","text":"Implementacja w pięciu językach","level":2,"locked":false},{"id":"push-czy-pull","text":"Push czy pull?","level":2,"locked":true},{"id":"pulapki-o-ktorych-milcza-diagramy","text":"Pułapki, o których milczą diagramy","level":2,"locked":true},{"id":"krotka-historia-obserwatora","text":"Krótka historia Obserwatora","level":2,"locked":true},{"id":"obserwator-a-publish-subscribe","text":"Obserwator a Publish/Subscribe","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},{"id":"cwiczenie","text":"Ćwiczenie","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":42,"visibleBlocks":15,"resources":[{"id":"6b0857a53c96f2d34d0b321b","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=_BpmfnqjgzQ","embedUrl":"https://www.youtube-nocookie.com/embed/_BpmfnqjgzQ","title":"Observer Pattern – Design Patterns (ep 2)","description":"","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/_BpmfnqjgzQ/hqdefault.jpg","durationSec":null,"lang":"en","topics":["observer"],"techs":["general"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:37.479Z","updatedAt":"2026-11-26T16:00:37.479Z"},{"id":"6b0857c23c96f2d34d0b4629","type":"article","provider":"web","url":"https://learn.microsoft.com/pl-pl/dotnet/standard/events/observer-design-pattern","embedUrl":null,"title":"Wzorzec projektowy obserwatora - .NET","description":"Dowiedz się więcej o wzorcu projektowania obserwatora na platformie .NET. Ten wzorzec umożliwia subskrybentowi rejestrowanie się i odbieranie powiadomień od dostawcy.","author":"Microsoft Learn","thumbnailUrl":"https://learn.microsoft.com/dotnet/media/dot-net-cross-platform.png","durationSec":null,"lang":"pl","topics":["observer"],"techs":["dotnet"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":50,"verifiedAt":"2026-11-26T11:26:51.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857bf3c96f2d34d0b4284","type":"article","provider":"web","url":"https://gameprogrammingpatterns.com/observer.html","embedUrl":null,"title":"Observer · Design Patterns Revisited · Game Programming Patterns","description":"","author":"Robert Nystrom","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":["observer"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":65,"verifiedAt":"2026-11-26T11:26:36.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T23:13:50.362Z"},{"id":"6b0857b63c96f2d34d0b3ade","type":"podcast","provider":"apple-podcasts","url":"https://podcasts.apple.com/us/podcast/703-the-observer-pattern/id1253186678?i=1000638170776","embedUrl":"https://embed.podcasts.apple.com/us/podcast/id1253186678?i=1000638170776","title":"703: The Observer Pattern","description":"In this episode of Syntax, Wes and Scott give a high level overview of the observer pattern, what is the observer, what are downsides to too many observers, and more. Show Notes 00:25 Welcome 01:42 Syntax Brought to you by Sentry 02:16 High level overview Syntax 694: What’s Up With Angular with…","author":"Syntax - Tasty Web Development Treats","thumbnailUrl":"https://is1-ssl.mzstatic.com/image/thumb/Podcasts221/v4/14/0a/50/140a50d8-f974-6542-e6d5-8362701cde23/mza_16091458091864441720.jpeg/600x600bb.jpg","durationSec":1162,"lang":"en","topics":["observer"],"techs":["typescript"],"tags":["podcast","performance","design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"itunes","publishedAt":"2023-12-11T11:00:00.000Z","popularity":76,"verifiedAt":"2026-11-26T10:57:52.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:53.924Z","updatedAt":"2026-11-26T16:00:53.924Z"},{"id":"6b0857c33c96f2d34d0b4666","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL16942701W","embedUrl":null,"title":"Head First design patterns","description":"","author":"Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates","thumbnailUrl":"https://covers.openlibrary.org/b/id/388950-L.jpg","durationSec":null,"lang":"en","topics":["factory-method","abstract-factory","builder","prototype","singleton","adapter","bridge","composite","decorator","facade","flyweight","proxy","chain-of-responsibility","command","iterator","mediator","memento","observer","state","strategy","template-method","visitor"],"techs":["java"],"tags":["book","design-patterns"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2004-01-01T00:00:00.000Z","popularity":62,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"}],"challenges":[{"id":"6b0857af5a2625e44ecaad10","slug":"order-observer","title":"Obserwator zamówień","summary":"Zamówienie powiadamia subskrybentów o zmianie statusu; subskrypcję da się anulować, a dziennik audytu zapisuje przejścia.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":null,"status":"published","difficulty":"medium","topics":["observer"],"techs":["dotnet","typescript"],"tags":["observer","events","behavioral"],"languages":["csharp","typescript"],"questionCount":null,"xp":20,"stats":{"attempts":1,"solves":1,"solutions":1,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.864Z"},{"id":"6b093ddebd4755deb67ee06b","slug":"event-emitter","title":"Własny EventEmitter","summary":"Piszemy uproszczony odpowiednik `EventEmitter` z Node.js – on, once, off, emit i specjalne zdarzenie `error`. Wzorzec Obserwator w praktyce, z pułapkami modyfikacji listy w trakcie emisji.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"easy","topics":["observer"],"techs":["typescript","javascript","python"],"tags":["design","events","observer","node","javascript"],"languages":["typescript","javascript","python"],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:54.007Z"},{"id":"6b093dc191bd8fbaf2a0c8d0","slug":"inventory-cqrs","title":"Magazyn z CQRS – osobny model zapisu i odczytu","summary":"Komendy magazynowe walidowane na własnym modelu zapisu, zdarzenia na szynie i projekcja budująca model odczytu z raportem niskich stanów. Model odczytu da się odtworzyć z samych zdarzeń.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"architecture","status":"published","difficulty":"medium","topics":["cqrs","event-driven-architecture"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["cqrs","read-model","projection","events","inventory"],"languages":["typescript","javascript","python","csharp","java","go"],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:25.519Z"},{"id":"6b0857af5a2625e44ecaad13","slug":"design-patterns-basics-quiz","title":"Wzorce projektowe – podstawy","summary":"Sześć pytań o klasyczne wzorce GoF: grupy, przeznaczenie i różnice.","servedLang":"pl","availableLangs":["pl","en"],"kind":"quiz","category":null,"status":"published","difficulty":"easy","topics":["builder","adapter","strategy","decorator","composite","facade","observer"],"techs":["general"],"tags":["quiz","gof","basics"],"languages":[],"questionCount":6,"xp":10,"stats":{"attempts":1,"solves":1,"solutions":0,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.960Z"}],"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":true},{"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":false}]}],"prev":{"slug":"strategy","title":"Strategia (Strategy): wymienne algorytmy zamiast drabinki if-ów"},"next":{"slug":"command","title":"Polecenie (Command): żądanie zamknięte w obiekcie"},"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}]}}