Observer pattern
medium 50 minDecouple a state-holding subject from its dependents: they register, and the subject notifies everyone on its list when something changes.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Who is on the list, who is called, and what can happen during a round.
Operations
Weather station
Register, change, notify, leave. Arrows are the entries of the list.
Step 1 of 10
Nobody listens
Nobody is told
The station knows 72 F and 65 percent. The list is empty.
Step 1: Nobody listens
class WeatherStation: def attach(self, o): self._observers.append(o) def detach(self, o): self._observers.remove(o) def set_measurements(self, t, h): self._temperature, self._humidity = t, h for o in list(self._observers): o.update(t, h)class PhoneDisplay: def update(self, t, h): self.show(t)- Watch
- The arrows
- Result
- Only those on the list
No arrow leads to a class the station knows by name.
In the real world
The same observer pattern doing real jobs. Pick one and step through it.
Settings live long, dialogs live short.
Step 1 of 4
Open
Dialog 1 attaches.
Step 1: Open
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Looping over the live list
criticalWho leaves during a round makes the next one skipped, or Java throws.
Wrongfor o in self._observers: o.update(v)Rightfor o in list(self._observers): if o in self._observers: o.update(v)Notify before store
criticalAn observer that asks back gets the old value.
Wrongself._notify(new)self._value = newRightself._value = newself._notify(new)Nobody detaches
criticalThe observer is never freed and goes on reacting.
Wrongsettings.attach(dialog.on_change)Rightself._stop = settings.attach(self.on_change)# and in close():self._stop()Swallowed errors
majorA broken observer looks healthy.
Wrongexcept Exception: passRightexcept Exception as error: self._on_error(event, error)Calling under a lock
criticalTwo locks can wait for each other.
Wrongwith self._lock: for o in self._observers: o.update(v)Rightwith self._lock: round = tuple(self._observers)for o in round: o.update(v)A step disguised as an observer
majorIf reserving stock fails, nobody stops the order.
Wrongorder.paid.attach(reserve_stock)Rightreserve_stock(order) # a stepcommit(order)order.paid.notify(order) # reactions
Interview tips
A safe round
- Store first.
- Copy the list.
- Catch each call.
Leaving
- Attach returns a handle.
- An owner closes it.
- Twice is harmless.
The message
- Immutable.
- Past tense.
- Equal is not news.
Threads
- No lock in calls.
- Bounded queues.
- A rule for dropping.
Is it an observer?
- Result matters: step.
- Order matters: step.
- Otherwise: react.