观察者模式(有时又被称为发布(publish-订阅(Subscribe)模式、模型-视图(View)模式、源-收听者(Listener)模式或从属者模式)是软件设计模式的一种。在此种模式中,一个目标物件管理所有相依于它的观察者物件,并且在它本身的状态改变时主动发出通知。这通常透过呼叫各观察者所提供的方法来实现。此种模式通常被用来实现事件处理系统。
观察者模式中包含以下几种对象类型:
# coding:utf-8
import weakref
class Subject(object):
"""被观察对象,使用列表存储所有观察者"""
def __init__(self, name):
"""此处使用弱引用,当删除observer是,WeakSet也会自动删除对应对象"""
self.name = name
self._observers = weakref.WeakSet()
def register_observer(self, observer):
"""订阅事件,相当于将观察者添加到列表中"""
self._observers.add(observer)
print "observer {0} now listening on {1}".format(observer.name, self.name)
def notify_observers(self, msg):
"""遍历列表,发送消息给每一个观察者"""
print("subject notifying observers about {}".format(msg,))
for observer in self._observers:
observer.notify(self, msg)
class Observer(object):
def __init__(self, name):
self.name = name
def start_observing(self, subject):
"""订阅事件"""
subject.register_observer(self)
def notify(self, subject, msg):
"""通知观察者"""
print "{0} get msg from {1} that {2}".format(self.name, subject.name, msg)
class_homework = Subject("class homework")
student1 = Observer("student 1")
student2 = Observer("student 2")
student1.start_observing(class_homework)
student2.start_observing(class_homework)
class_homework.notify_observers("result if out")
del student1
class_homework.notify_observers("20/20 passed this exam")
输出结果为:
observer student 1 now listening on class homework
observer student 2 now listening on class homework
subject notifying observers about result if out
student 1 get msg from class homework that result if out
student 2 get msg from class homework that result if out
subject notifying observers about 20/20 passed this exam
student 2 get msg from class homework that 20/20 passed this exam