装饰(Decorator)模式的定义:指在不改变现有对象结构的状况下,动态地给该对象增长一些职责(即增长其额外功能)的模式,它属于对象结构型模式。python
装饰(Decorator)模式的主要优势有:spa
其主要缺点是:装饰模式增长了许多子类,若是过分使用会使程序变得很复杂。设计
一般状况下,扩展一个类的功能会使用继承方式来实现。但继承具备静态特征,耦合度高,而且随着扩展功能的增多,子类会很膨胀。code
若是使用组合关系来建立一个包装对象(即装饰对象)来包裹真实对象,并在保持真实对象的类结构不变的前提下,为其提供额外的功能,这就是装饰模式的目标。component
下面来分析其基本结构和实现方法:对象
装饰模式主要包含如下角色。blog
装饰模式的实现代码以下:继承
class Component(object): def operation(self): pass class ConcreteComponent(Component): def operation(self): print('ConcreteComponent') class Decorator(Component): __component = None def __init__(self, component): self.__component = component def operation(self): self.__component.operation() class ConcreteDecorator(Decorator): def __init__(self, component): super().__init__(component) def operation(self): super().operation() self.added_function() def added_function(self): print("add contents") if __name__ == '__main__': p = ConcreteComponent() p.operation() print('----------------------add something-------------------') d = ConcreteDecorator(p) d.operation()
用装饰模式实现游戏角色“莫莉卡·安斯兰”的变身。接口
分析:在《恶魔战士》中,游戏角色“莫莉卡·安斯兰”的原身是一个可爱少女,但当她变身时,会变成头顶及背部延伸出蝙蝠状飞翼的女妖,固然她还能够变为穿着漂亮外衣的少女。游戏
这些均可用装饰模式来实现,在本实例中的“莫莉卡”原身有 setImage(String t) 方法决定其显示方式,而其 变身“蝙蝠状女妖”和“着装少女”能够用 setChanger() 方法来改变其外观,原身与变身后的效果用 display() 方法来显示,
图所示是其结构图。
class Morrigan(object): def display(self): pass class Original(Morrigan): def display(self): print('Original Morrigan') class Changer(Morrigan): __original = None def __init__(self, original): self.__original = original def display(self): self.__original.display() class Succybus(Changer): def __init__(self, original): super().__init__(original) def set_changer(self): print('Succybus Morrigan') def display(self): super().display() print('↓↓↓↓↓↓↓↓↓↓↓') self.set_changer() class Girl(Changer): def __init__(self, original): super().__init__(original) def set_changer(self): print('Girl Morrigan') def display(self): super().display() print('↓↓↓↓↓↓↓↓↓↓↓') self.set_changer() if __name__ == '__main__': o = Original() o.display() s = Succybus(o) s.display() g = Girl(o) g.display()
前面讲解了关于装饰模式的结构与特色,下面介绍其适用的应用场景,装饰模式一般在如下几种状况使用。
装饰模式所包含的 4 个角色不是任什么时候候都要存在的,在有些应用环境下模式是能够简化的,如如下两种状况。
(1) 若是只有一个具体构件而没有抽象构件时,可让抽象装饰继承具体构件,其结构图如图所示。
(2) 若是只有一个具体装饰时,能够将抽象装饰和具体装饰合并,其结构图如图所示。