第6章:装饰模式
装饰模式
装饰模式(decorator):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
Component
定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent
定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator
装饰抽象类,继承了Component
,从外类来扩展Component
类的功能。但对于Component
来说,是无需知道Decorator
的存在的。至于ConcreteComponent
就是具体的装饰对象,起到给Component
添加职责的功能。
Component
类
ConcreteComponent
类
Decorator
类
ConcreteDecoratorA
类
- 客户端代码
装饰模式是利用SetComponent
来对对象进行包装的,这样每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。
如果只有一个ConcreteComponent
类而没有抽象的Component
类,那么Decorator
类可以是ConcreteComponent
的一个子类。同样道理,如果只有一个ConcreteDecorator
类,那么就没有必要建立一个单独的Decorator
类,而可以把Decorator
和ConcreteDecorator
的责任合并成一个类。
装饰模式示例
任务:Avatar服饰搭配
from typing import Text
# Person类(ConcreteComponent)
class Person(object):
def __init__(self, name: Text) -> None:
self.name = name
def show(self) -> None:
print("装扮的",self.name)
# 服饰类(Decorator)
class Finery(Person):
def __init__(self) -> None:
self.component = None
def set_component(self, component: Person) -> None:
self.component = component
def show(self):
if self.component:
self.component.show()
# 具体服饰类(ConcreteDecorator)
class TShirt(Finery):
def show(self) -> None:
print("T恤")
super(TShirt, self).show()
class BigTrousers(Finery):
def show(self) -> None:
print("垮裤")
super(BigTrousers, self).show()
class Sneakers(Finery):
def show(self) -> None:
print("球鞋")
super(Sneakers, self).show()
class Suit(Finery):
def show(self) -> None:
print("西装")
super(Suit, self).show()
class Tie(Finery):
def show(self) -> None:
print("领带")
super(Tie, self).show()
class LeatherShoes(Finery):
def show(self) -> None:
print("皮鞋")
super(LeatherShoes, self).show()
# 客户端代码
if __name__ == "__main__":
person = Person("cai")
print("第一种装扮")
sneakers = Sneakers()
big_trousers = BigTrousers()
t_shirt = TShirt()
# 装饰过程
sneakers.set_component(person)
big_trousers.set_component(sneakers)
t_shirt.set_component(big_trousers)
t_shirt.show()
print()
print("第二种装扮")
suit = Suit()
tie = Tie()
leather_shoes = LeatherShoes()
# 装饰过程
leather_shoes.set_component(person)
tie.set_component(leather_shoes)
suit.set_component(tie)
suit.show()
第一种装扮
T恤
垮裤
球鞋
装扮的 cai
第二种装扮
西装
领带
皮鞋
装扮的 cai
装饰模式总结
装饰模式是为已有功能动态地添加更多功能的一种方式。
装饰模式使用场景:当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为,但这种做法的问题在于,它们在主类中加入了新的字段,新的方法和新的逻辑。从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。
装饰模式提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了
装饰模式的优点:把类中的装饰功能从类中搬移去除,这样可以简化原有的类,有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。