|
| 1 | +from abc import ABCMeta, abstractstaticmethod |
| 2 | +from enum import Enum |
| 3 | +import time |
| 4 | + |
| 5 | + |
| 6 | +class WeatherType(Enum): |
| 7 | + SUNNY = 1 |
| 8 | + RAINY = 2 |
| 9 | + WINDY = 3 |
| 10 | + COLD = 4 |
| 11 | + |
| 12 | + |
| 13 | +class Weather(): |
| 14 | + """Observable""" |
| 15 | + |
| 16 | + def __init__(self): |
| 17 | + self._observers = set() |
| 18 | + pass |
| 19 | + |
| 20 | + def register(self, observer): |
| 21 | + self._observers.add(observer) |
| 22 | + |
| 23 | + def remove_observer(self, observer): |
| 24 | + self._observers.remove(observer) |
| 25 | + |
| 26 | + def notify(self, weather_type): |
| 27 | + for observer in self._observers: |
| 28 | + observer.update(weather_type) |
| 29 | + |
| 30 | + |
| 31 | +class IObserver(metaclass=ABCMeta): |
| 32 | + |
| 33 | + @abstractstaticmethod |
| 34 | + def update(WeatherType): |
| 35 | + """Update all the registered observers""" |
| 36 | + |
| 37 | + |
| 38 | +class BBCWeather(IObserver): |
| 39 | + def __init__(self, observable): |
| 40 | + observable.register(self) |
| 41 | + |
| 42 | + def update(self, weather_type): |
| 43 | + print(f"{__class__} : {repr(weather_type)}") |
| 44 | + |
| 45 | + |
| 46 | +class ABCWeather(IObserver): |
| 47 | + def __init__(self, observable): |
| 48 | + observable.register(self) |
| 49 | + |
| 50 | + def update(self, weather_type): |
| 51 | + print(f"{__class__} : {repr(weather_type)}") |
| 52 | + |
| 53 | + |
| 54 | +class NBCWeather(IObserver): |
| 55 | + def __init__(self, observable): |
| 56 | + observable.register(self) |
| 57 | + |
| 58 | + def update(self, weather_type): |
| 59 | + print(f"{__class__} : {repr(weather_type)}") |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + |
| 64 | + WEATHERSERVICE = Weather() |
| 65 | + |
| 66 | + BBCWEATHER = BBCWeather(WEATHERSERVICE) |
| 67 | + ABCWEATHER = ABCWeather(WEATHERSERVICE) |
| 68 | + NBCWEATHER = NBCWeather(WEATHERSERVICE) |
| 69 | + |
| 70 | + WEATHERSERVICE.notify(WeatherType.RAINY) |
| 71 | + WEATHERSERVICE.remove_observer(BBCWEATHER) |
| 72 | + time.sleep(2) |
| 73 | + WEATHERSERVICE.notify(WeatherType.SUNNY) |
| 74 | + WEATHERSERVICE.remove_observer(NBCWEATHER) |
| 75 | + time.sleep(2) |
| 76 | + WEATHERSERVICE.notify(WeatherType.WINDY) |
| 77 | + time.sleep(2) |
| 78 | + WEATHERSERVICE.notify(WeatherType.COLD) |
0 commit comments