原文是《大话设计模式》,许多代码参考博主 ponder008
单一职责原则:就一个类而言,应该仅有一个引起它变化的原因。一个类应该只有一个功能。
开放-封闭原则:软件实体(类、模块、函数等等)应该可以扩展,但不可以修改。对扩展是开放的,对修改是封闭的。面对需求,对程序的改动是通过增加新代码进行的,而不是更改现有的代码。
开发人员应该仅对程序中呈现出频繁变化的那些部分做出抽象,然而,对于应用程序中的每个部分都刻意地进行抽象同样不是一个好主意。拒绝不成熟的抽象和抽象本身一样重要。
依赖倒转原则:高层模块不应该依赖底层模块。两个都应该依赖抽象。抽象不应该依赖细节,细节应该依赖抽象。
里氏代换原则:子类型必须能够替换掉他们的父类型。
迪米特法则(最少知识原则):如果两个类不必彼此直接通信,那么这两个类就不应当发生直接的相互作用。如果一个类需要调用另一个类的某一个方法的话,可以通过第三者转发这个调用。
迪米特法则首先强调的前提是,在类的结构设计上,每一个类都应当尽量降低成员的访问权限。
"""简单工厂模式"""
class Operation:
def __init__(self, num1=None, num2=None):
self.num1 = num1
self.num2 = num2
def getresult(self):
pass
class OperationAdd(Operation):
def getresult(self):
return self.num1 + self.num2
class OperationSub(Operation):
def getresult(self):
return self.num1 - self.num2
class OperationMul(Operation):
def getresult(self):
return self.num1 * self.num2
class OperationDiv(Operation):
def getresult(self):
if self.num2 == 0:
return "错误"
else:
return self.num1 / self.num2
class Factory:
@staticmethod
def result(ops):
if ops == "+":
return OperationAdd()
elif ops == "-":
return OperationSub()
elif ops == "*":
return OperationMul()
elif ops == "/":
return OperationDiv()
if __name__ == "__main__":
nu1 = int(input("第一个数"))
op = input("加减乘除")
nu2 = int(input("第二个数"))
res = Factory().result(ops=op)
res.num1 = nu1
res.num2 = nu2
print(res.getresult())
"""策略模式"""
class Market:
def __init__(self, price=None):
self.price = price
def preferential(self):
pass
class Discount(Market):
def preferential(self):
return self.price * 0.8
class Subtract(Market):
def preferential(self):
return self.price - (self.price // 100) * 10
if __name__ == "__main__":
total_list = []
n = 0
while n != "1":
unit_price = eval(input("商品单价"))
count = eval(input("数量"))
total_price = unit_price * count
total_list.append(total_price)
n = input("输入 1 停止")
price = sum(total_list)
s = int(input("请选择优惠方式\n1 八折\n2 满100减10元\n"))
if s == 1:
result = Discount(price=price).preferential()
print("最后结果 %d" % result)
if s == 2:
result = Subtract(price=price).preferential()
print("最后结果 %d" % result)
"""装饰模式"""
class Person:
def __init__(self, name):
self.name = name
def show(self):
print("装扮的%s" % self.name)
class Decorator(Person):
def __init__(self, name):
super().__init__(name)
self.component = None
def decorate(self, component):
self.component = component
def show(self):
if self.component is not None:
self.component.show()
class T_Shirt(Decorator):
def __init__(self):
super().__init__(self)
print("短袖")
class Pants(Decorator):
def __init__(self):
super().__init__(self)
print("长裤")
if __name__ == "__main__":
xc = Person(name="小菜")
dx = T_Shirt()
ck = Pants()
dx.decorate(xc)
ck.decorate(dx)
ck.show()
"""代理模式"""
class Go_girl:
def __init__(self, name):
self.name = name
class IGive:
def give_flowers(self):
pass
def give_dolls(self):
pass
class pursuit(IGive, Go_girl):
def give_flowers(self):
print("送花给%s" % self.name)
def give_dolls(self):
print("送洋娃娃给%s" % self.name)
class Proxy(IGive):
def __init__(self, name):
self.name = name
def give_flowers(self):
pursuit(self.name).give_flowers()
def give_dolls(self):
pursuit(self.name).give_dolls()
if __name__ == "__main__":
li = Go_girl("林允儿")
proxy = Proxy(li.name)
proxy.give_flowers()
proxy.give_dolls()
"""工厂方法模式"""
class LeiFeng:
def sweep(self):
pass
def buy(self):
pass
class Student(LeiFeng):
def sweep(self):
print("学生扫地")
def buy(self):
print("学生买米")
class Volunteer(LeiFeng):
def sweep(self):
print("志愿者扫地")
def buy(self):
print("志愿者买米")
class IFactory:
def create(self):
pass
class student_factory(IFactory):
def create(self):
return Student()
class volunteer_factory(IFactory):
def create(self):
return Volunteer()
if __name__ == "__main__":
student = student_factory().create()
student.buy()
student.sweep()
volunteer = volunteer_factory().create()
volunteer.buy()
volunteer.sweep()
"""原型模式"""
import copy
class ICloneable:
def shallowClone(self):
return copy.copy(self)
def deepClone(self):
return copy.deepcopy(self)
class WorkExperience(ICloneable):
workData = ""
company = ""
pass
class Resume(ICloneable):
name = ""
sex = ""
age = 0
work = None
def __init__(self, name, work=WorkExperience()):
self.name = name
self.work = work
def setPersonInfo(self, sex, age):
self.sex = sex
self.age = age
def setWorkExperience(self, workData, company):
self.work.workData = workData
self.work.company = company
def display(self):
print('%s, %s, %d' % (self.name, self.sex, self.age))
print('%s, %s' % (self.work.workData, self.work.company))
if __name__ == "__main__":
a = Resume('大鸟')
a.setPersonInfo('男', 29)
a.setWorkExperience("1998-2000", "XX公司")
# 浅拷贝
b = a.shallowClone()
b.setWorkExperience("2000-2006", "YY公司")
# 深拷贝
c = a.deepClone()
c.setWorkExperience("2006-2009", "ZZ公司")
b.display()
a.display()
c.display()
"""模板方法模式"""
class test:
def __init__(self):
self.answer1 = None
self.answer2 = None
self.answer3 = None
def test1(self):
print("杨过得到,后来给了郭靖,炼成倚天剑、屠龙刀的玄铁可能是[] a.球磨铸铁"
"b.马口铁 c.高速合金钢 d.碳素纤维")
def test2(self):
print("杨过、程英、陆无双铲除了情花,造成[] a.使这种植物不再害人 b.使一种珍稀物种灭绝"
"c.破坏了生物圈的生态平衡 d.造成该地区沙漠化")
def test3(self):
print("蓝凤凰致使华山师徒、桃谷六仙呕吐不止,如果你是大夫,会给他们开什么药[ ] "
"a.阿司匹林 b.牛黄解毒片 c.氟哌酸 d.让他们喝大量的牛奶 e.以上全不对")
class Student(test):
def answer(self, a, b, c):
self.answer1 = a
self.answer2 = b
self.answer3 = c
return self.answer1, self.answer2, self.answer3
if __name__ == "__main__":
studentA = Student().answer("b", "c", "a")
print("A学生的答案是 {}".format(studentA))
studentB = Student().answer("c", "a", "a")
print("B学生的答案是 {}".format(studentB))
class studentA(test):
def test1(self):
return "A"
def test2(self):
return "B"
def test3(self):
return "C"
if __name__ == "__main__":
print(studentA().test1())
"""外观模式"""
class Stock(object):
@staticmethod
def buy():
print("买股票")
@staticmethod
def sell():
print("卖股票")
class NationalDebt(object):
@staticmethod
def buy():
print("买国债")
@staticmethod
def sell():
print("卖国债")
class Realty(object):
@staticmethod
def buy():
print("房地产买入")
@staticmethod
def sell():
print("房地产卖出")
class Fund(object):
st = Stock()
na = NationalDebt()
re = Realty()
def buy(self):
self.st.buy()
self.na.buy()
self.re.buy()
def sell(self):
self.st.sell()
self.na.sell()
self.re.sell()
if __name__ == "__main__":
fund = Fund()
fund.buy()
fund.sell()
"""建造者模式"""
class build:
def body(self):
pass
def head(self):
pass
def leftleg(self):
pass
def rightleg(self):
pass
def leftarm(self):
pass
def rightarm(self):
pass
class fat_person(build):
pass
class Burger:
name = ""
def getname(self):
return self.name
class Cheeseburger(Burger):
def __init__(self):
self.name = "奶酪汉堡"
class Chickenburger(Burger):
def __init__(self):
self.name = "鸡腿堡"
class Beverage:
name = ""
def getname(self):
return self.name
class coke(Beverage):
def __init__(self):
self.name = "可乐"
class milk(Beverage):
def __init__(self):
self.name = "牛奶"
class order:
burger = ""
beverage = ""
def __init__(self, builder):
self.burger = builder.bburger
self.beverage = builder.bbeverage
def show(self):
print("burger:%s" % self.burger.getname())
print("beverage:%s" % self.beverage.getname())
class orderbuilder:
bburger = ""
bbeverage = ""
def addburger(self, xburger):
self.bburger = xburger
def addbeverage(self, xbeverage):
self.bbeverage = xbeverage
def build(self):
return order(self)
class orderdirector():
def __init__(self, order_builder):
self.order_builder = order_builder
def createorder(self, burger, beverage):
self.order_builder.addburger(burger)
self.order_builder.addbeverage(beverage)
return self.order_builder.build()
if __name__ == "__main__":
build = orderbuilder()
# build.addburger(Chickenburger())
# build.addbeverage(milk())
# order1 = build.build()
# order1.show()
build1 = orderdirector(build).createorder(Chickenburger(), milk())
build1.show()
"""观察者模式"""
"""
第一版
检查半天,结果是,print少了个括号
"""
class Notice:
server_list = []
def __init__(self, server):
self.server = server
def attach(self, name):
self.server_list.append(name)
return self.server_list
def notify(self):
for i in self.server_list:
Server(i, self.server).update()
class Server:
sub = Notice
def __init__(self, serve, sub):
self.serve = serve
self.sub = sub
def update(self):
print("%s:%s继续工作" % (self.sub, self.serve))
if __name__ == "__main__":
re = Notice("小童")
re.attach("小李")
re.attach("小张")
re.notify()
"""第二版,大致就是这样,增加了抽象父类,通知者和观察者都可灵活添加类"""
class Notice:
server_list = []
def __init__(self, server):
self.server = server
def attach(self, name):
pass
def detach(self, name):
pass
def notify(self):
pass
class helper(Notice):
def attach(self, name):
self.server_list.append(name)
def detach(self, name):
self.server_list.remove(name)
def notify(self):
for i in self.server_list:
NBAserve(i, self.server).update()
class server:
def __init__(self, serve, sub):
self.serve = serve
self.sub = sub
def update(self):
pass
class NBAserve(server):
def update(self):
print("%s:%s好好工作" % (self.sub, self.serve))
if __name__ == "__main__":
notic = helper("老板")
notic.attach("小李")
notic.attach("小白")
notic.detach("小李")
notic.notify()
"""抽象工厂模式"""
# class User:
# userid = None
# user_name = None
#
# def ID(self, userid):
# self.userid = userid
# return userid
#
# def name(self, user_name):
# self.user_name = user_name
# return user_name
class User:
def insert(self):
pass
def select(self):
pass
class sqlserver(User):
def insert(self):
print("sqlserver增")
def select(self):
print("sqlserver查")
class access(User):
def insert(self):
print("access增")
def select(self):
print("access查")
class Factory:
def create(self):
pass
class sqlserverfactory(Factory):
def create(self):
return sqlserver()
class accessfactory(Factory):
def create(self):
return access()
if __name__ == "__main__":
re = accessfactory().create()
re.select()
re.insert()
"""状态模式"""
class state:
def program(self, h):
pass
class morning(state):
def program(self, h):
if h.hour < 12:
print("精力充沛")
else:
h.setstate(noon())
h.program()
class noon(state):
def program(self, h):
if h.hour < 13:
print("午休")
else:
h.setstate(afternoon())
h.program()
class afternoon(state):
def program(self, h):
if h.hour < 18:
print("下午还行")
else:
h.setstate(evening())
h.program()
class evening(state):
def program(self, h):
if h.finish:
h.setstate(go_home())
h.program()
elif h.hour < 21:
print("加班")
else:
h.setstate(sleep())
h.pregram()
class go_home(state):
def program(self, h):
print("下班回家")
class sleep(state):
def program(self, h):
print("睡觉")
class work:
state = morning()
finish = False
hour = 8
def setstate(self, state):
self.state = state
def program(self):
self.state.program(self)
if __name__ == "__main__":
a = work()
a.hour = 18
a.finish = True
a.program()
"""适配器模式"""
class player:
def __init__(self, name):
self.name = name
def attack(self):
pass
def defense(self):
pass
class forwards(player):
def attack(self):
print("%s进攻" % self.name)
def defense(self):
print("%s防守" % self.name)
class foreign:
def __init__(self, name):
self.name = name
def f_attack(self):
print("%s外籍进攻" % self.name)
def f_defence(self):
print("%s外籍防守" % self.name)
class translater(player):
def __init__(self, name):
super().__init__(name)
self.ym = foreign(self.name)
def attack(self):
self.ym.f_attack()
def defense(self):
self.ym.f_defence()
if __name__ == "__main__":
ym = translater("姚明")
ym.attack()
ym.defense()
"""备忘录模式"""
class gamePlayer:
vitality = 0
attack = 0
defense = 0
def state(self):
print("当前状态")
print("生命值\t%s" % self.vitality)
print("攻击力\t%s" % self.attack)
print("防御力\t%s" % self.defense)
def initstate(self):
self.vitality = 100
self.attack = 100
self.defense = 100
def fight(self):
self.vitality = 0
self.attack = 0
self.defense = 0
def savestate(self):
return memento(self.vitality, self.attack, self.defense)
def readstate(self, mementos):
self.vitality = mementos.vitality
self.attack = mementos.attack
self.defense = mementos.defense
class memento:
vitality = 0
attack = 0
defense = 0
def __init__(self, vitality, attack, defense):
self.vitality = vitality
self.attack = attack
self.defense = defense
class setstate:
memento = None
if __name__ == "__main__":
player = gamePlayer()
player.initstate()
print("大战前夕")
player.state()
print("存档")
getstate = setstate()
getstate.memento = player.savestate()
player.fight()
print("战败")
player.state()
print("读档")
player.readstate(getstate.memento)
player.state()
"""组合模式"""
class root:
def add(self, child):
pass
def remove(self, child):
pass
def show(self, depth):
pass
class leaf(root):
def __init__(self, name):
self.name = name
def add(self, child):
print("不能添加分支")
def remove(self, child):
print("不能减少分支")
def show(self, depth):
print("-" * depth, self.name)
class branch(root):
def __init__(self, name):
self.name = name
self.children = []
def add(self, child):
self.children.append(child)
def remove(self, child):
self.children.remove(child)
def show(self, depth):
print("-" * depth, self.name)
for i in self.children:
i.show(depth + 2)
if __name__ == "__main__":
root = branch("root")
root.add(leaf("a"))
root.add(leaf("b"))
com = branch("ab")
com.add(leaf("abx"))
com.add(leaf("aby"))
root.add(com)
new_leaf = leaf("c")
root.add(new_leaf)
root.remove(new_leaf)
root.show(1)
class company:
def add(self, child):
pass
def remove(self, child):
pass
def show(self, depth):
pass
def line_print(self):
pass
class create_company(company):
def __init__(self, name):
self.name = name
self.company_list = []
def add(self, child):
self.company_list.append(child)
def remove(self, child):
self.company_list.remove(child)
def show(self, depth):
print("-" * depth, self.name)
for i in self.company_list:
i.show(depth + 2)
def line_print(self):
for e in self.company_list:
e.line_print()
class hr(company):
def __init__(self, name):
self.name = name
def show(self, depth):
print("-" * depth, self.name)
def line_print(self):
print("%s hr部门" % self.name)
if __name__ == "__main__":
root = create_company("天津总公司")
root.add(hr("邯郸"))
root.show(1)
root.line_print()
"""迭代器模式"""
class iterator:
def first(self):
pass
def next(self):
pass
def done(self):
pass
def current(self):
pass
class aggregate:
def create_iterator(self):
pass
class create_iterator(iterator):
count = 0
def __init__(self, list):
self.list = list
def first(self):
return self.list[0]
def next(self):
ret = None
self.count += 1
if self.count < len(self.list):
self.ret = self.list[self.count]
return ret
def done(self):
if self.count >= len(self.list):
return False
else:
return True
def current(self):
if self.count < len(self.list):
return self.list[self.count]
class create_aggregate(aggregate):
items = None
def __init__(self):
self.items = []
if __name__ == "__main__":
s = create_aggregate()
s.items.append("大鸟")
s.items.append("小菜")
s.items.append("小偷")
s.items.append("歪果仁")
a = create_iterator(s.items)
a.first()
while a.done() == True:
print("%s买票" % a.current())
a.next()
"""单例模式"""
class musicPlayer:
instance = None
def __new__(cls, *args, **kwargs):
if cls.instance is None:
print("创建空间")
cls.instance = super().__new__(cls)
return cls.instance
def __init__(self):
print("播放器初始化")
if __name__ == "__main__":
a = musicPlayer()
b = musicPlayer()
print(a)
print(b)
"""
饿汉式单例类:在类被加载时就将自己实例化(静态初始化)。优点是躲避了多线程的安全性问题,缺点是提前占用系统资源
懒汉式单例类:在第一次被引用时才将自己实例化。避免开始时占用系统资源,但是有多线程访问安全性问题
以下是多线程双重锁定单例(懒汉式单例的多线程访问解决方式)
"""
import threading
class singleton:
instance = None
mutex = threading.Lock()
@staticmethod
def getinstance():
if singleton.instance is None:
singleton.mutex.acquire()
if singleton.instance is None:
print("单例初始化")
singleton.instance = singleton()
else:
print("已经初始化")
singleton.mutex.release()
else:
print("已经初始化")
return singleton.instance
if __name__ == "__main__":
singleton.getinstance()
singleton.getinstance()
"""桥接模式"""
class software:
def run(self):
pass
class game(software):
def run(self):
print("运行游戏")
class address(software):
def run(self):
print("运行通讯录")
class phone:
def __init__(self):
self.soft = None
def setSoftware(self, soft):
self.soft = soft
def run(self):
pass
class NPhone(phone):
def run(self):
self.soft.run()
class MPhone(phone):
def run(self):
self.soft.run()
if __name__ == "__main__":
phone = NPhone()
phone.setSoftware(game())
phone.run()
tele = MPhone()
tele.setSoftware(address())
tele.run()
"""命令模式"""
class barbecuer:
def mutton(self):
print("烤羊肉串")
def chickenwing(self):
print("烤鸡翅")
class command:
def __init__(self, commandx):
self.commandx = commandx
def execute(self):
pass
def string(self):
pass
class muttoncommand(command):
def execute(self):
self.commandx.mutton()
def string(self):
return "烤羊肉串"
class chickenwingcommand(command):
def execute(self):
self.commandx.chickenwing()
def string(self):
return "烤鸡翅"
class waiter:
command_list = []
def setorder(self, commands):
self.command_list.append(commands)
print("增加订单:%s" % commands.string())
def cancelorder(self, commands):
self.command_list.remove(commands)
print("取消订单:%s" % commands.string())
def notify(self):
for i in self.command_list:
i.execute()
if __name__ == "__main__":
boy = barbecuer()
jichi = chickenwingcommand(boy)
rouchuan = muttoncommand(boy)
girl = waiter()
girl.setorder(jichi)
girl.setorder(rouchuan)
girl.notify()
"""职责链模式"""
class manager:
def __init__(self, name):
self.superior = None
self.name = name
self.successor = None
def setsuperior(self, superior):
self.superior = superior
def request(self, request):
pass
class common(manager):
def request(self, request):
if request.type == "请假" and request.number <= 2:
print("%s:%s 数量%s 批准" % (self.name, request.content, request.number))
else:
if self.superior is not None:
self.superior.request(request)
class majordomo(manager):
def request(self, request):
if request.type == "请假" and request.number <= 5:
print("%s:%s 数量%s 批准" % (self.name, request.content, request.number))
else:
if self.superior is not None:
self.superior.request(request)
class general(manager):
def request(self, request):
if request.type == "请假" and request.number <= 7:
print("%s:%s 数量%s 批准" % (self.name, request.content, request.number))
elif request.type == "涨工资" and request.number <= 500:
print("%s:%s 数量%s 批准" % (self.name, request.content, request.number))
else:
print("%s:%s 数量%s 再说吧" % (self.name, request.content, request.number))
class Request:
type = ""
number = 0
content = ""
if __name__ == "__main__":
jingli = common("金立")
zongjian = majordomo("宗建")
zongjingli = general("钟金利")
jingli.setsuperior(zongjian)
zongjian.setsuperior(zongjingli)
req = Request()
req.type = "请假"
req.number = 2
req.content = "小菜请假"
jingli.request(req)
re1 = Request()
re1.type = "涨工资"
re1.number = 500
re1.content = "小菜想涨工资500块钱"
jingli.request(re1)
re2 = Request()
re2.type = "请假"
re2.number = 8
re2.content = "小菜想请假八天"
jingli.request(re2)
"""中介者模式"""
class united:
def declare(self, message, colleague):
pass
class country:
def __init__(self, mediator):
self.mediator = mediator
class usa(country):
def declare(self, message):
self.mediator.declare(message, self)
@staticmethod
def notify(message):
print("美国得到对方消息:%s" % message)
class iraq(country):
def declare(self, message):
self.mediator.declare(message, self)
@staticmethod
def notify(message):
print("伊拉克得到对方消息:%s" % message)
class unitedmediator(united):
colleague1 = None
colleague2 = None
def declare(self, message, colleague):
if colleague == self.colleague1:
self.colleague2.notify(message)
else:
self.colleague1.notify(message)
if __name__ == "__main__":
m = unitedmediator()
c1 = usa(m)
c2 = iraq(m)
m.colleague1 = c1
m.colleague2 = c2
c1.declare("不准研发核武器,否则要发动战争")
c2.declare("我们没有核武器,也不怕侵略")
"""享元模式"""
class website:
def use(self, user):
pass
class concretewebsite(website):
def __init__(self, name):
self.name = name
def use(self, user):
print("网站分类:%s 用户:%s" % (self.name, user))
class factory:
websites = {}
def getwebsite(self, key):
if (key in self.websites.keys()) is False:
self.websites[key] = concretewebsite(key)
return self.websites[key]
def getcount(self):
return len(self.websites)
if __name__ == "__main__":
f = factory()
fx = f.getwebsite("产品展示")
fy = f.getwebsite("博客")
fz = f.getwebsite("微博")
fx.use("小菜")
fy.use("旺财")
"""解释器模式"""
class playcontent:
text = None
playtext = None
class expression:
def interpret(self, context):
if len(context.playtext) == 0:
return
else:
playkey = context.playtext[0:1]
context.playtext = context.playtext[2:]
tmp = context.playtext.index(" ")
playvalue = context.playtext[0:tmp]
context.playtext = context.playtext[tmp + 1:]
self.execute(playkey, playvalue)
def execute(self, playkey, playvalue):
pass
class pitch(expression):
pitch = None
def execute(self, playkey, playvalue):
value = int(playvalue)
if value == 1:
self.pitch = "低音"
elif value == 2:
self.pitch = "中音"
elif value == 3:
self.pitch = "高音"
print(self.pitch)
class note(expression):
notes = {
"C": 1,
"D": 2,
"E": 3,
"F": 4,
"G": 5,
"A": 6,
"B": 7
}
note = None
def execute(self, playkey, playvalue):
self.note = self.notes[playkey]
print(self.note)
if __name__ == "__main__":
content = playcontent()
content.playtext = "O 2 E 0.5 G 0.5 A 3 E 0.5 G 0.5 D 3 E 0.5 G 0.5 A 0.5 O 3 C 1 O 2 A 0.5 G 1 C 0.5 E 0.5 D 3 "
while len(content.playtext) > 0:
str = content.playtext[0:1]
if str == "O":
expression = pitch()
if str == "C" or str == "D" or str == "E" or str == "F" or str == "G" or str == "A" or str == "B":
expression = note()
expression.interpret(content)
"""访问者模式"""
class action:
def getmanconclusion(self, man):
pass
def getwomanconclusion(self, woman):
pass
class person:
def accept(self, act):
pass
class man(person):
type = "男人"
def accept(self, act):
act.getmanconclusion(self)
class woman(person):
type = "女人"
def accept(self, act):
act.getwomanconclusion(self)
class success(action):
type = "成功"
def getmanconclusion(self, man):
print("%s%s时,背后多半有一个伟大的女人" % (man.type, self.type))
def getwomanconclusion(self, woman):
print("%s%s时,背后多半有一个不太成功的男人" % (woman.type, self.type))
class fail(action):
type = "失败"
def getmanconclusion(self, man):
print("%s%s时,闷头喝酒,谁也不用劝" % (man.type, self.type))
def getwomanconclusion(self, woman):
print("%s%s时,眼泪汪汪,谁也劝不了" % (woman.type, self.type))
if __name__ == "__main__":
xiaoming = man()
xiaohong = woman()
success = success()
xiaoming.accept(success)
xiaohong.accept(success)
"""
加个列表
"""
class structure:
structure_list = []
def attach(self, element):
self.structure_list.append(element)
def remove(self, element):
self.structure_list.remove(element)
def display(self, visitor):
for i in self.structure_list:
i.accept(visitor)
if __name__ == "__main__":
man1 = man()
woman1 = woman()
structure = structure()
structure.attach(man1)
structure.attach(woman1)
fail = fail()
structure.display(fail)