Observer Pattern
The Observer pattern: letting many objects subscribe to one and be told when it changes, and the listener that is never unsubscribed.
A placed order must send an email, reduce the stock and record a sale; a changed temperature must update every display; a click must reach every handler that cares. In each case one object changes and several others must react, and the object that changed should not have to know who they are. The Observer pattern lets the others subscribe to it, and it calls every subscriber when it changes.
This topic opens on the code that calls each dependant by name, then reads the participants off the class diagram and follows one change through a sequence diagram. The template attaches two observers, detaches one, and changes the subject in Python, Java and TypeScript.
Two examples follow: an order service whose subscribers email, update stock and keep the takings, and Node's EventEmitter, the same shape as the browser's addEventListener. A comparison shows a plain list of functions doing the subject's job in Python. The gotcha is the lapsed listener, an object that was never unsubscribed and so is never freed, and the exercise finds one in a temperature sensor.
By the end you can recognise an observer, implement one, and diagnose a subscriber that outlives its use.
Contents
9 cardsnot started