使用场景
建造过程不稳定,不确定。把所需的功能按照正确的顺序串联起来进行控制。
新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。装饰模式把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象。
定义
动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
装饰模式结构图
- Component是定义一个对象接口,可以给这个对象动态添加职责,对应下文python实现中的Persion类
- Decorator继承Component类,是通过具体装饰类抽象出来的一个类,对应下文python实现中的Finery类
- ConcreteDecoratorA/ConcreteDecoratorB类,就是具体的装饰对象,继承自Decorator类,动态的给Component添加职责,对应下文python实现中的TShirt/BigTrouser/Sneaker
python实现装饰模式
#coding=utf-8
import os
class Person:
def __init__(self, name):
self.name = name
def show(self):
print('打扮的' + self.name)
class Finery(Person):
def __init__(self):
self.component = None
def decorate(self, component):
self.component = component
def show(self):
if self.component is not None:
self.component.show()
class TShirt(Finery):
def show(self):
print '大T恤',
self.component.show()
class BigTrouser(Finery):
def show(self):
print '垮裤',
self.component.show()
class Sneaker(Finery):
def show(self):
print '运动鞋',
self.component.show()
if __name__ == '__main__':
p = Person('大熊')
upClothes = TShirt()
downClothes = BigTrouser()
shoes = Sneaker()
upClothes.decorate(p)
downClothes.decorate(upClothes)
shoes.decorate(downClothes)
shoes.show()
- 执行结果
运动鞋 垮裤 大T恤 打扮的大熊
代码结构图
优点
把类中的装饰功能从类中搬移去除,这样可以简化原有的类。有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。
装饰顺序很重要。