`

python 设计模式之 - 行为模式

阅读更多
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')



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics