这是python高级编程中的一个例子,看了下,觉得很容易理解 ,和很容易使用,尤其是里面还用到了我上篇文章 写的那个classmethod,分享上来。
因为我关于设计模式的学习是在C#中哦给你完成的,所以对于在python中使用设计模式,喜欢用C#的思维来套,这其实是错误的方式。
在python中,类是对象,函数也是对象。因此不必非要用class来定义观者者。
#coding=utf-8
'''
author:the5fire
date:2012-7-17
'''
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:
cls._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
class AnotherObserver(object):
def __call__(self, event):
print 'Yeah %s told me !' % event
if __name__ == '__main__':
WriteEvent.register(log)
WriteEvent.register(AnotherObserver())
WriteEvent.notify('a given file')
print '============'
print WriteEvent('test')
- from the5fire.com
----EOF-----
微信公众号:Python程序员杂谈
微信公众号:Python程序员杂谈