-- flyaflya [2005-08-04 09:28:01]

1. Visitor(访问者)

1.1. 意图

作用于某个对象群中各个对象的操作. 它可以使你在不改变这些对象本身的情况下,定义作用于这些对象的新操作.

1.2. 代码

   1 class Visitor:
   2     def __init__(self):
   3         self._methodDic={}
   4 
   5     def default(self, other):
   6         print "What's this:", other
   7 
   8     def addMethod(self, method):
   9         self._methodDic[method.getKey()]=method
  10 
  11     def __call__(self, other):
  12         method=self._methodDic.get(\
                other.__class__.__name__,self.default)
  13         return method(other)

1.3. 例子

MyVisit的函数call中定义对target的具体访问操作。

   1 class MyVisit:
   2     """
   3     Instead of deriving from Visitor the work is
   4     done by instances with this interface.
   5     """
   6     def __init__(self, otherClass):
   7         self._msg='Visit: %s'%otherClass.__name__
   8         self._key=otherClass.__name__
   9 
  10     def __call__(self, target):
  11         print self._msg, target
  12 
  13     def getKey(self):
  14         return self._key
  15 
  16 # 被访问者
  17 class E1:pass
  18 class E2:pass
  19 class E3:pass
  20 
  21 # 用法
  22 
  23 collection=[E1(), E1(), E2(), E3()]
  24 
  25 visitor=Visitor()
  26 visitor.addMethod(MyVisit(E1))
  27 visitor.addMethod(MyVisit(E2))
  28 
  29 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>

# 简化用法

   1 visitor = Visitor()
   2 visitor.addMethod(MyVisit(E1))
   3 a = E1()
   4 visitor(a)

输出:

Visit: E1 <__main__.E1 instance at 0x00A91EE0> 

1.4. 特殊说明