Observer pattern#
Reference: エキスパートPythonプログラミング 改訂3版; 第17章 Pythonのためのデザインパターン
class Event:
_observers = []
def __init__(self, subject):
self.subject = subject
@classmethod
def register(cls, observer):
if observer not in cls._observers:
cls._observers.append(observer)
@classmethod
def unregister(cls, observer):
if observer in cls._observers:
cls._observers.remove(observer)
@classmethod
def notify(cls, subject):
event = cls(subject)
for observer in cls._observers:
observer(event)
class WriteEvent(Event):
def __repr__(self):
return 'WriteEvent'
def log(event):
print(f'{event} was fired by the subject "{event.subject}"')
class AnotherObserver:
def __call__(self, event):
print(f'{event} called the action "{self.__class__.__name__}"')
WriteEvent.register(log)
WriteEvent.register(AnotherObserver())
WriteEvent.notify('Something happened')
WriteEvent was fired by the subject "Something happened"
WriteEvent called the action "AnotherObserver"