现在的位置: 主页 > 商讯 > 文章列表

访问者模式(python)

作者:兴义市全盈商贸有限公司 来源:www.cnlianguo.com 发布时间:2017-09-11 14:05:37
 

访问者模式(python)



"""
访问者模式
状态模式复杂版,状态模式是一个复杂对象有多个分支,然后把这些分支抽象成状态,在运行时根据状态来执行;
而访问者模式是多个复杂对象有同样多的分支,且复杂对象的个数相对稳定,不然到时候就修改该分支状态类的代码
"""
from abc import ABCMeta, abstractmethod
class Person(object):
__metaclass__ = ABCMeta
def __init__(self, name):
self.name = name
pass
@abstractmethod
def display(self, state):
pass
class Man(Person):
def __init__(self, name):
super(Man, self).__init__(name)
def display(self, state):
state.man_display(self)
class Woman(Person):
def __init__(self, name):
super(Woman, self).__init__(name)
def display(self, state):
state.woman_display(self)
class State(object):
__metaclass__ = ABCMeta
def __init__(self):
pass
@abstractmethod
def man_display(self, man):
pass
@abstractmethod
def woman_display(self, woman):
pass
class Marry(State):
def __init__(self):
super(Marry, self).__init__()
def man_display(self, man):
print("男人结婚如进坟墓")
print("{0},你好可伶".format(man.name))
print("")
def woman_display(self, woman):
print("女人结婚好幸福")
print("{0},你好幸福".format(woman.name))
print("")
class Work(State):
def __init__(self,):
super(Work, self).__init__()
def man_display(self, man):
print("男人工作说起来都是泪")
print("{0},你好可伶".format(man.name))
print("")
def woman_display(self, woman):
print("女人工作就是玩")
print("{0},你好幸福".format(woman.name))
print("")
class Creator(object):
def __init__(self):
self.person_list = []
pass
def append(self, person):
self.person_list.append(person)
def display(self, state):
for person in self.person_list:
person.display(state)
if __name__ == '__main__':
creator = Creator()
creator.append(Man("张三"))
creator.append(Woman("翠翠"))
marry = Marry()
work = Work()
creator.display(marry)
creator.display(work)

企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:荆州网站建设 http://jingzhou.45qun.com

  • 上一篇:bluehost虚拟空间主机安装Discuz! X3论坛图文教程
  • 下一篇:最后一页
  •