## page was renamed from zhArticleTemplate ##language:zh #pragma section-numbers on -- flyaflya [<>] <> == Visitor(访问者) == === 意图 === 作用于某个对象群中各个对象的操作. 它可以使你在不改变这些对象本身的情况下,定义作用于这些对象的新操作. === 代码 === {{{ #!python class Visitor: def __init__(self): self._methodDic={} def default(self, other): print "What's this:", other def addMethod(self, method): self._methodDic[method.getKey()]=method def __call__(self, other): method=self._methodDic.get(\ other.__class__.__name__,self.default) return method(other) }}} === 例子 === 在MyVisit的函数__call__中定义对target的具体访问操作。 {{{ #!python class MyVisit: """ Instead of deriving from Visitor the work is done by instances with this interface. """ def __init__(self, otherClass): self._msg='Visit: %s'%otherClass.__name__ self._key=otherClass.__name__ def __call__(self, target): print self._msg, target def getKey(self): return self._key # 被访问者 class E1:pass class E2:pass class E3:pass # 用法 collection=[E1(), E1(), E2(), E3()] visitor=Visitor() visitor.addMethod(MyVisit(E1)) visitor.addMethod(MyVisit(E2)) map(visitor, collection) }}} ########################### 输出: {{{Visit: E1 <__main__.E1 instance at 7ff6d0> Visit: E1 <__main__.E1 instance at 7ff730> Visit: E2 <__main__.E2 instance at 7ff780> What's this: <__main__.E3 instance at 7ff7b0> }}} # 简化用法 {{{ #!python visitor = Visitor() visitor.addMethod(MyVisit(E1)) a = E1() visitor(a) }}} ######################### 输出: {{{Visit: E1 <__main__.E1 instance at 0x00A91EE0> }}} === 特殊说明 ===