装饰模式,动态地给一个对象添加一些额外得职责,就增加功能来说,装饰模式比生成子类更为灵活。
装饰模式结构图
开发过程中什么时候会用到装饰模式
在系统需要新功能的时候,是向旧的类中添加新的代码。这些新的代码通常装饰了原有类的核心职责或主要行为。这样子做的好处,有效地把类的核心职责和装饰功能区分开了。
参照UML的结构图,设计一个带有装饰模式的事例代码。
class Person:
"""Component"""
def operation(self, name):
pass
class Student(Person):
"""ConcreteComponent"""
def operation(self, name):
print(name)
class Decorator(Person):
"""Decorator"""
component = Person()
# 利用set_person 来对对象进行包装的
def set_component(self, component):
self.component = component
def operation(self, name):
pass
class DecoratorA(Decorator):
"""ConcreteDecorator"""
name = "装饰器A"
def eat_something(self):
print("eat_something:"+self.name)
def operation(self, name):
# 旧有代码的核心逻辑
self.component.operation(name)
# 新增加的代码
self.eat_something()
class DecoratorB(Decorator):
name = "装饰器B"
"""ConcreteDecorator"""
def operation(self, name):
# 旧有的核心逻辑
self.component.operation(name)
# 新增加的逻辑
print(self.name)
if __name__ == "__main__":
student = Student()
decorator_a = DecoratorA()
decorator_a.set_component(student)
decorator_a.operation("decorator_a:"+"裤衩")
decorator_b = DecoratorB()
decorator_b.set_component(decorator_a)
decorator_b.operation("decorator_b:"+"帽子")