Docs

Design Patterns — Fast Recall (Python)

Observer — notify subscribers on change


  • What: a subject keeps a list of observers and pushes updates to all of them when its state changes (pub/sub).
  • Why / when: one-to-many reactions — UI re-render on data change, event systems, notifications, cache invalidation.
  • Benefit: subject and observers are loosely coupled — subject doesn't know who's listening.
  • Gotcha: unsubscribe or you leak memory / update dead objects; beware update storms (cascading notifications).
1class Subject: 2 def __init__(self): self.subs = [] 3 def subscribe(self, fn): self.subs.append(fn) 4 def emit(self, data): 5 for fn in self.subs: fn(data) # notify all 6 7s = Subject() 8s.subscribe(lambda d: print("A got", d)) 9s.subscribe(lambda d: print("B got", d)) 10s.emit("event!") # A got event! / B got event!