python设计模式(观察者模式)

来源:互联网 发布:经典书籍推荐知乎 编辑:程序博客网 时间:2024/06/08 03:39
#学习版本3.5.2#观察者模式,它定义了一种一对多的依赖关系,让多个观察者同时监听某一个对象。这个#对象的状态发生变化时候,会通知所有的观察者,是他们能够得到最新的信息#例如:一个个奸细同时在监视小明,在他的身上安装的定位class Person(object):    def __init__(self):        self._observerlist = []    #被偷偷安装监视器    def attach(self, observer):        self._observerlist.append(observer)    #去除监视器    def detach(self, observer):        self._observerlist.remove(observer)    def notify(self, location):        for obs in self._observerlist:            obs.update(location)class Observer(object):    def update(self, message):        print("get infomation: ",message)if __name__ == "__main__":    observer = Observer()    xiaoming = Person()    xiaoming.attach(observer)    xiaoming.notify("go to beijing")

运行结果

get infomation:  go to beijing


原创粉丝点击