标签:style blog http color java os io for ar
访问者模式即表示一个作用于某对象结构中的各元素的操作,它使我们可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
说明:男人、女人被成功、失败‘访问’的反应
代码:
# -*- coding: cp936 -*- class Person: def Accept(self,visitor): pass class Man(Person): def Accept(self,visitor): visitor.GetManConclusion(self) class Woman(Person): def Accept(self,visitor): visitor.GetWomanConclusion(self) class Action: def GetManConclusion(self,concreteElementA): pass def GetWomanConclusion(self,concreteElementB): pass class Success(Action): def GetManConclusion(self,concreteElementA): print "男人成功时,背后有个伟大的女人" def GetWomanConclusion(self,concreteElementB): print "女人成功时,背后有个不成功的男人" class Failure(Action): def GetManConclusion(self,concreteElementA): print "男人失败时,闷头喝酒,谁也不用劝" def GetWomanConclusion(self,concreteElementB): print "女人失败时,眼泪汪汪,谁也劝不了" #class ObjectStructure: # def __init__(self): # self.plist=[] # def Add(self,p): # self.plist=self.plist+[p] # def Display(self,act): # for p in self.plist: # p.Accept(act) #if __name__ == "__main__": # os = ObjectStructure() # os.Add(Man()) # os.Add(Woman()) # sc = Success() # os.Display(sc) # fl = Failure() # os.Display(fl) if __name__ == "__main__": man=Man() woman=Woman() sc =Success() fl =Failure() man.Accept(sc) woman.Accept(sc) man.Accept(fl) woman.Accept(fl)
运行结果:
http://www.cnblogs.com/chenssy/p/3679190.html
http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html
http://www.cnblogs.com/java-my-life/archive/2012/06/14/2545381.html
标签:style blog http color java os io for ar
原文地址:http://www.cnblogs.com/wang-shuai/p/3935353.html