[size=large][b][color=red]Vistor 模式:[/color]
[/b] [/size]
[size=large]Vistor 模式常常用于将访问数据,支持传入不同的数据访问器(或是处理器),上例子[/size]
[size=large][b][color=red]Observer 模式:[/color]
[/b] [/size]
[size=large]Observer 模式常常用于侦听对象发生的变化,上例子[/size]
[/b] [/size]
[size=large]Vistor 模式常常用于将访问数据,支持传入不同的数据访问器(或是处理器),上例子[/size]
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
[size=large][b][color=red]Observer 模式:[/color]
[/b] [/size]
[size=large]Observer 模式常常用于侦听对象发生的变化,上例子[/size]
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')