Python设计模式观察者模式
分享主题:Python 设计模式之观察者模式
定义
观察者模式也叫发布订阅模式,定义了对象之间一对多依赖,当一个对象改变状态时,这个对象的所有依赖者都会收到通知并按照自己的方式进行更新。
观察者设计模式是最简单的行为模式之一。在观察者设计模式中,对象(主题)维护了一个依赖(观察者)列表,以便主题可以使用观察者定义的任何方法通知所有观察者它所发生的变化。
举个生活中的小例子:职员们趁老板不在,都在搞着自己与工作无关的事情,同时观察着前台小姐姐,前台小姐姐在老板回来的时候,发布通知让各同事回到工作状态。
使用场景
在广播或者发布订阅系统的情形中,你会看到观察者设计模式的用法,它的主要使用场景如下: 在分布式系统中实现事件服务。 用作新闻机器的框架。 股票市场也是观察者模式的一个大型场景。
主要目标它定义了对象之间的一对多的依赖关系,从而使得一个对象中的任何更改都将自动通知给其他依赖的对象。 它封装了主题的核心组件。
代码实现1、创建观察者类1class Watcher: 2 #初始化具体的成员 3 def __init__(self,id,name): 4 self.id=id 5 self.name=name 6 7 #向具体的成员发送消息的方法 8 def send(self,msg): 9 print(str(self.name)+ "-" + str(self.id)+" recive the message is: "+msg) 2、创建主题类 1class Subject: 2 #初始化一个主题列表 3 def __init__(self): 4 self.queues=[] 5 6 #将订阅者添加到队列中 7 def add_queue(self,sub): 8 self.queues.append(sub) 9 return self.queues 10 11 #从订阅的主题里面移除 12 def remove_queue(self,sub): 13 self.queues.remove(sub) 14 self.queues 15 16 #发送通知给相关的主题订阅者 17 def notice(self,msg): 18 for queue in self.queues: 19 queue.send(msg) 20 21if __name__ == "__main__": 22 #实例化具体的Watcher对象,用于去订阅和接收相关信息 23 tom=Watcher(1001,"tom") 24 tony=Watcher(1002,"tony") 25 jack=Watcher(1003,"jack") 26 27 #实例化Subject对象,定义为添加天气主题 28 weather=Subject() 29 weather.add_queue(tom) 30 weather.add_queue(tony) 31 32 #实例化Subject对象,定义为添加军事主题 33 military=Subject() 34 military.add_queue(tony) 35 military.add_queue(jack) 36 37 #给订阅者发布天气消息 38 weather.notice("it"s rain") 39 military.notice("it"s peace") 40 41 #将tony从weather and military主题中取消订阅 42 weather.remove_queue(tony) 43 military.remove_queue(tony) 44 45 #取消订阅后给剩下的订阅者发布消息 46 weather.notice("it"s windy") 47 military.notice("it"s war") 3、执行结果输出1tom-1001 recive the message is: it"s rain 2tony-1002 recive the message is: it"s rain 3tony-1002 recive the message is: it"s peace 4jack-1003 recive the message is: it"s peace 5tom-1001 recive the message is: it"s windy 6jack-1003 recive the message is: it"s war