Паттерн Наблюдатель задаёт зависимость «один ко многим»: когда меняется субъект, все его наблюдатели уведомляются автоматически. Субъект знает лишь маленький интерфейс наблюдателя, поэтому реакции (табло, оповещение, журнал) можно добавлять и убирать во время работы, не меняя его.

`PriceTicker` уведомляет `Display` и `Alert` через протокол `Observer`
PriceTicker уведомляет Display и Alert через протокол Observer

Субъект и наблюдатели

У субъекта три задачи: subscribe, unsubscribe и notify. Здесь PriceTicker уведомляет после каждого set_price. Display печатает каждую цену, Alert — только выше своего лимита.

python
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)
text
display: 101
display: 110
ALERT: above 105

Push или pull