every blog every motto: You can do more than you think.
https://blog.csdn.net/weixin_39190382?type=blog
0. 前言
装饰模式
1. 第一版
class Person:
def __init__(self, name):
self.name = name
def wear_t_shirts(self):
print("大T恤 ", end="")
def wear_big_trouser(self):
print("垮掉 ", end="")
def wear_sneakers(self):
print("破球鞋 ", end="")
def wear_suit(self):
print("西装 ", end="")
def wear_tie(self):
print("领带 ", end="")
def wear_leather_shoes(self):
print("皮鞋 ", end="")
def show(self):
print(f"装扮的{self.name}")
# 客户端代码
if __name__ == "__main__":
xc = Person("小菜")
print("\n第一种装扮: ")
xc.wear_t_shirts()
xc.wear_big_trouser()
xc.wear_sneakers()
xc.show()
print("\n第二种装扮: ")
xc.wear_suit()
xc.wear_tie()
xc.wear_leather_shoes()
xc.show()
input() # 相当于C#的Console.Read()
增加"超人"类,需要修改Person,违反了开放-封闭原则
2. 第二版
from abc import ABC, abstractmethod
# Person 类
class Person:
def __init__(self, name):
self.name = name
def show(self):
print(f"装扮的{self.name}")
# 服饰抽象类
class Finery(ABC):
@abstractmethod
def show(self):
pass
# 具体服饰类
class TShirts(Finery):
def show(self):
print("大T恤 ", end="")
class BigTrouser(Finery):
def show(self):
print("垮裤 ", end="")
class Sneakers(Finery):
def show(self):
print("破球鞋 ", end="")
class Suit(Finery):
def show(self):
print("西装 ", end="")
class Tie(Finery):
def show(self):
print("领带 ", end="")
class LeatherShoes(Finery):
def show(self):
print("皮鞋 ", end="")
# 客户端代码
if __name__ == "__main__":
xc = Person("小菜")
print("\n第一种装扮:")
dtx = TShirts()
kk = BigTrouser()
pgx = Sneakers()
dtx.show()
kk.show()
pgx.show()
xc.show()
print("\n第二种装扮:")
xz = Suit()
ld = Tie()
px = LeatherShoes()
xz.show()
ld.show()
px.show()
xc.show()
建造者模式过程必须稳定,而这里建造过程不稳定,可以先传西装,外套,也可以反过来。
3. 第三版
装饰模式
from abc import ABC, abstractmethod
# Person类 (ConcreteComponent)
class Person:
def __init__(self, name):
self.name = name
def show(self):
print(f"装扮的{self.name}")
# 服饰抽象类 (Decorator)
class Finery(Person):
def __init__(self):
self._component = None
# 打扮/装饰方法
def decorate(self, component):
self._component = component
def show(self):
if self._component:
self._component.show()
# 具体服饰类 (ConcreteDecorator)
class TShirts(Finery):
def show(self):
print("大T恤 ", end="")
super().show()
class BigTrouser(Finery):
def show(self):
print("垮裤 ", end="")
super().show()
class Sneakers(Finery):
def show(self):
print("破球鞋 ", end="")
super().show()
class Suit(Finery):
def show(self):
print("西装 ", end="")
super().show()
class Tie(Finery):
def show(self):
print("领带 ", end="")
super().show()
class LeatherShoes(Finery):
def show(self):
print("皮鞋 ", end="")
super().show()
# 客户端代码
if __name__ == "__main__":
xc = Person("小菜")
print("\n第一种装扮:")
pqx = Sneakers()
kk = BigTrouser()
dtx = TShirts()
pqx.decorate(xc) # 装饰过程
kk.decorate(pqx)
dtx.decorate(kk)
dtx.show()
print("\n第二种装扮:")
px = LeatherShoes()
ld = Tie()
xz = Suit()
px.decorate(xc) # 装饰过程
ld.decorate(px)
xz.decorate(ld)
xz.show()
input() # 相当于C#的Console.Read()