Back
+15 XP
Concept

The Observer Pattern: Event Dispatches

The Observer pattern establishes a one-to-many dependency. When subject state changes, all registered observer callbacks are notified automatically 📡.

python
class EventBus:
    def __init__(self):
        self.subscribers = []

    def subscribe(self, callback):
        self.subscribers.append(callback)

    def dispatch(self, event_name):
        for sub in self.subscribers:
            sub(event_name)

bus = EventBus()
bus.subscribe(lambda e: print(f"Audit log: {e} 📜"))
bus.subscribe(lambda e: print(f"Push alert: {e} 🔔"))
bus.dispatch("USER_LOGGED_IN")

# 118. The Observer Pattern: Event Dispatches The Observer pattern establishes a one-to-many dependency. When subject state changes, all registered observer callbacks are notified automatically 📡. ```python class EventBus: def __init__(self): self.subscribers = [] def subscribe(self, callback): self.subscribers.append(callback) def dispatch(self, event_name): for sub in self.subscribers: sub(event_name) bus = EventBus() bus.subscribe(lambda e: print(f"Audit log: {e} 📜")) bus.subscribe(lambda e: print(f"Push alert: {e} 🔔")) bus.dispatch("USER_LOGGED_IN") ``` The Observer pattern powers GUI button clicks, WebSocket pub/sub message brokers, and distributed event-driven microservices! 📡 --- ### Question How does the Observer pattern decouple event emitters from event listeners? 🧠 - [ ] a. The emitter simply notifies a list of subscriber callbacks without knowing what they do 📡 - [ ] b. Subscribers run inside separate virtual machines - [ ] c. Events are serialized into XML files on disk - [ ] d. It requires all callbacks to be async coroutines --- ### Challenge Write class `Dispatcher` with `self.listeners = []`. Add `register(self, fn)` and `notify(self, data)` returning `[fn(data) for fn in self.listeners]`. Register `lambda x: x * 2`. Call `notify(5)` and print. 🎯 <details> <summary>Solution</summary> ```python class Dispatcher: def __init__(self): self.listeners = [] def register(self, fn): self.listeners.append(fn) def notify(self, data): return [fn(data) for fn in self.listeners] d = Dispatcher() d.register(lambda x: x * 2) print(d.notify(5)) ``` </details>

Checkpoint

How does the Observer pattern decouple event emitters from event listeners? 🧠

Practice

Write class `Dispatcher` with `self.listeners = []`. Add `register(self, fn)` and `notify(self, data)` returning `[fn(data) for fn in self.listeners]`. Register `lambda x: x * 2`. Call `notify(5)` and print. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks