from abc import ABC, abstractmethod
class Observer(ABC):
@abstractmethod
def update(self, temperature):
pass
class Subject(ABC):
@abstractmethod
def attach(self, observer: Observer):
pass
@abstractmethod
def detach(self, observer: Observer):
pass
@abstractmethod
def notify(self):
pass
class WeatherStation(Subject):
def __init__(self):
self._observers = []
self._temperature = 0
def attach(self, observer: Observer):
self._observers.append(observer)
def detach(self, observer: Observer):
self._observers.remove(observer)
def notify(self):
for observer in self._observers:
observer.update(self._temperature)
def set_temperature(self, temperature):
print(f"WeatherStation: Setting temperature to {temperature}")
self._temperature = temperature
self.notify() # Оповещаем всех наблюдателей
class PhoneDisplay(Observer):
def update(self, temperature):
print(f"PhoneDisplay: The temperature is now {temperature}°C")
class WindowDisplay(Observer):
def update(self, temperature):
print(f"WindowDisplay: The temperature is now {temperature}°C")
def main():
# Создаем наблюдаемый объект
weather_station = WeatherStation()
# Создаем наблюдателей
phone_display = PhoneDisplay()
window_display = WindowDisplay()
# Подписываем наблюдателей на обновления
weather_station.attach(phone_display)
weather_station.attach(window_display)
# Изменяем температуру, чтобы оповестить наблюдателей
weather_station.set_temperature(25)
weather_station.set_temperature(30)
# Отключаем одного наблюдателя и снова изменяем температуру
weather_station.detach(window_display)
weather_station.set_temperature(20)
main()
WeatherStation: Setting temperature to 25
PhoneDisplay: The temperature is now 25°C
WindowDisplay: The temperature is now 25°C
WeatherStation: Setting temperature to 30
PhoneDisplay: The temperature is now 30°C
WindowDisplay: The temperature is now 30°C
WeatherStation: Setting temperature to 20
PhoneDisplay: The temperature is now 20°C