The Observer pattern defines a one-to-many dependency: when the subject changes, all its observers are notified automatically. The subject only knows the small observer interface, so reactions (a display, an alert, a log) can be added or removed at runtime without changing it.
Subject and observers
The subject has three jobs: subscribe, unsubscribe and notify. Here PriceTicker notifies after every set_price. Display prints each price, Alert only those above its limit.
class PriceTicker:
def __init__(self):
self._observers = []
self.price = 100
def subscribe(self, obs):
self._observers.append(obs)
def unsubscribe(self, obs):
self._observers.remove(obs)
def set_price(self, price):
self.price = price
for obs in list(self._observers): # a copy: observers may unsubscribe
obs.update(self) # pull style: pass the subject
class Display:
def update(self, ticker):
print("display:", ticker.price)
class Alert:
def __init__(self, limit):
self.limit = limit
def update(self, ticker):
if ticker.price > self.limit:
print("ALERT: above", self.limit)
ticker = PriceTicker()
ticker.subscribe(Display())
ticker.subscribe(Alert(105))
ticker.set_price(101)
ticker.set_price(110)display: 101
display: 110
ALERT: above 105