#encoding=utf-8
__author__ = 'kevinlu1010@qq测试数据'
class Receptionist():
def __init__(self):
self.observes=[]
self.status=''
def attach(self,observe):
self.observes.append(observe)
def notify(self):
for observe in self.observes:
observe.update()
class StockObserve():
def __init__(self,name,receptionist):
self.name=name
self.receptionist=receptionist
def update(self):
print '%s,%s停止看股票'%(self.receptionist.status,self.name)
if __name__=='__main__':
receptionist=Receptionist()
observe1=StockObserve('张三',receptionist)
observe2=StockObserve('李四',receptionist)
receptionist.attach(observe1)
receptionist.attach(observe2)
receptionist.status='老板来了'
receptionist.notify() #encoding=utf-8
__author__ = 'kevinlu1010@qq测试数据'
from abc import ABCMeta, abstractmethod
class Subject():
__metaclass__ = ABCMeta
observers=[]
status=''
@abstractmethod
def attach(self,observer):
pass
@abstractmethod
def detach(self,observer):
pass
@abstractmethod
def notify(self):
pass
class Observer():
__metaclass__ = ABCMeta
def __init__(self,name,sub):
self.name=name
self.sub=sub
@abstractmethod
def update(self):
pass
class Boss(Subject):
def __init__(self):
pass
def attach(self,observer):
self.observers.append(observer)
def detach(self,observer):
self.observers.remove(observer)
def notify(self):
for observer in self.observers:
observer.update()
class StockObserver(Observer):
def update(self):
print '%s,%s停止看股票'%(self.sub.status,self.name)
class NBAObserver(Observer):
def update(self):
print '%s,%s停止看NBA'%(self.sub.status,self.name)
if __name__=='__main__':
boss=Boss()
observe1=StockObserver('张三',boss)
observe2=NBAObserver('李四',boss)
boss.attach(observe1)
boss.attach(observe2)
boss.detach(observe2)
boss.status='我是老板,我来了'
boss.notify() 相关教程:Python视频教程
以上就是Python学习之观察者模式的详细内容,更多请关注Gxl网其它相关文章!
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did83363