Card 09/ 09
Recap: Observer Pattern
The subject keeps a list and calls it; whoever subscribes must also unsubscribe.
Observer lets any number of objects subscribe to one, and be called when it changes.
- Intent. Define a one-to-many dependency so that when one object changes, all its dependants are notified.
- Participants. The subject with
attach,detachandnotify; the observer interface withupdate; their concrete classes. - Push or pull.
updatecarries the new data, or the observer asks the subject for it. - In the wild. Node's
EventEmitterwithon,offandemit, and the browser'saddEventListener. - In Python. A list of callbacks is a subject; keep a reference to any callback you will remove.
- The trap. A lapsed listener keeps its object alive and still reacts; pair every attach with a detach.
- When not. One fixed dependant, reactions whose order matters, or chains of notifications nobody can follow.
← → move through sections and cards