observer pattern
09 Nov 2016 | python patternOverview
다음은 내맘대로 그려본 Observer pattern 의 시나리오이다.
생각해보니 MVC패턴에 적용하면 Controller를 Observable, View를 Observer로 놓을 수 있겠다. 다음은 코드이다.
class Observable(object):
def __init__(self):
self.observers = []
def register(self, observer):
if not observer in self.observers:
self.observers.append(observer)
def unregister(self, observer):
if observer in self.observers:
self.observers.remove(observer)
def unregister_all(self):
if self.observers:
del self.observers[:] # list의 모든 항목을 지우는 코드. list는 남는다.
def update_observers(self, *args, **kwargs):
for observer in self.observers:
observer.update(*args, **kwargs)
from abc import ABCMeta, abstractmethod
class Observer(object):
__metaclass__ = ABCMeta
@abstractmethod
def update(self, *args, **kwargs):
pass
from Observable import Observable
from Observer import Observer
class AmericanStockMarket(Observer):
def update(self, *args, **kwargs):
print("American stock market received: {0}\n{1}".format(args, kwargs))
class EuropeanStockMarket(Observer):
def update(self, *args, **kwargs):
print("European stock market received: {0}\n{1}".format(args, kwargs))
if __name__ == "__main__":
observable = Observable()
american_observer = AmericanStockMarket()
observable.register(american_observer)
european_observer = EuropeanStockMarket()
observable.register(european_observer)
observable.update_observers('Market Rally', something='Hello World')