允许向一个现有的对象添加新的功能,而且不改变类的结构。
Demo
"""
装饰器模式
"""
class Shape:
def draw(self):
raise NotImplementedError
class Circle(Shape):
def draw(self):
print("this is circle")
class ShapeDecorator:
def __init__(self, shape: Shape):
self.shape = shape
def draw(self):
self.shape.draw()
class RedShapeDecorator(ShapeDecorator):
def draw(self):
super(RedShapeDecorator, self).draw()
print('color is red')
if __name__ == '__main__':
c = Circle()
c.draw()
print("=" * 10)
red_c = RedShapeDecorator(Circle())
red_c.draw()