浏览 4489 次
锁定老帖子 主题:python 设计模式之 - 行为模式
精华帖 (0) :: 良好帖 (0) :: 新手帖 (1) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-01-12
最后修改:2011-01-12
Vistor 模式:
Vistor 模式常常用于将访问数据,支持传入不同的数据访问器(或是处理器),上例子 def visit(directory, visitor): for root, dirs, files in os.walk(directory): for f in files: ext = os.path.splitext(f)[-1][1:] if hasattr(visitor,ext): a = getattr(visitor,ext) a(f) class FileReader(object): """ File Reader """ def bmp(self,f): print "is bmc",f visit("d:\\eastmoney\\",FileReader()) is bmc btclose.bmp is bmc btclose2.bmp is bmc btclosedown.bmp is bmc btmax.bmp Observer 模式: Observer 模式常常用于侦听对象发生的变化,上例子 class Event(object): _observers = [] def __init__(self, subject): self.subject = subject @classmethod def register(cls, observer): if observer not in cls._observers: cls._observers.append(observer) @classmethod def unregister(cls, observer): if observer in cls._observers: self._observers.remove(observer) @classmethod def notify(cls, subject): event = cls(subject) for observer in cls._observers: observer(event) class WriteEvent(Event): def __repr__(self): return 'WriteEvent' def log(event): print '%s was written' % event.subject WriteEvent.register(log) WriteEvent.notify('a given file') 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |