装饰者模式
class Component:
def operator(self):
pass
class ConcreteComponent(Component):
def operator(self):
return "ConcreteComponent operator"
class Decorator(Component):
def __init__(self, component) -> None:
super().__init__()
self.component = component
def operator(self):
return self.component.operator()
class ConcreteDecoratorA(Decorator):
def operator(self):
return "DecoratorA " + super().operator()
class ConcreteDecoratorB(Decorator):
def operator(self):
return "DecoratorB " + super().operator()
# 鍒涘缓鍏蜂綋缁勪欢
component = ConcreteComponent()
print("Component: ", component.operator())
# 浣跨敤鍏蜂綋瑁呴グ鑰匒鍖呰缁勪欢
decorator_a = ConcreteDecoratorA(component)
print("Decorator A: ", decorator_a.operator())
# 浣跨敤鍏蜂綋瑁呴グ鑰匓鍖呰缁勪欢
decorator_b = ConcreteDecoratorB(component)
print("Decorator B: ", decorator_b.operator())
# 浣跨敤鍏蜂綋瑁呴グ鑰匒鍜孊鐨勭粍鍚堝寘瑁呯粍浠?
decorator_ab = ConcreteDecoratorA(ConcreteDecoratorB(component))
print("Decorator A + B: ", decorator_ab.operator())
可以极大的减少自学的成本