The Observer pattern lets one object announce a change to any number of other objects without knowing who they are.
It is how buttons tell your code they were clicked, and how a screen knows to redraw when its data changes.
The problem it solves
Picture a temperature sensor in a smart home app. When the reading changes, the display should update, an alarm should check whether it is too hot, and a logger should write the value down.
The obvious version has the sensor call each of them by name:
def set_temperature(self, value):
self.temperature = value
self.display.show(value)
self.alarm.check(value)
self.logger.write(value)It works, but the sensor now depends on three classes it has no reason to know about. Add a phone notification and you edit the sensor. Remove the logger and you edit the sensor again. The thing producing the change has become responsible for knowing everything that reacts to it.
The Observer pattern flips that around. The sensor keeps a list of whoever wants to hear about changes, and when something changes it tells everyone on the list. Who is on the list is their business, not the sensor's.
The two roles
- The subject (sometimes called the publisher or observable) owns some state and keeps a list of observers. It offers a way to subscribe, a way to unsubscribe, and it notifies every observer when its state changes.
Wondering how this was made? How we make these