Card 09/ 09

RecapDifficulty: Advanced1 min

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, detach and notify; the observer interface with update; their concrete classes.
  • Push or pull. update carries the new data, or the observer asks the subject for it.
  • In the wild. Node's EventEmitter with on, off and emit, and the browser's addEventListener.
  • 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.