The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods .
“观察者模式”:__被观察者对象__通过一个列表维护__观察者对象__的行为(方法),当__被观察者对象__状态改变时会主动呼叫(调用)__观察者对象__行为(方法)。
PS:观察者模式有时又被称为发布(publish)-订阅(Subscribe)模式、模型-视图(View)模式、源-收听者(Listener)模式或从属者模式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ''' Python示例代码,来自网络 ''' class Observable : def __init__ (self ): self.__observers = [] def register_observer (self, observer ): self.__observers.append(observer) def notify_observers (self, *args, **kwargs ): for observer in self.__observers: observer.notify(self, *args, **kwargs) class Observer : def __init__ (self, observable ): observable.register_observer(self) def notify (self, observable, *args, **kwargs ): print('Got' , args, kwargs, 'From' , observable) subject = Observable() observer = Observer(subject) subject.notify_observers('test' )