This article was done using my notes from:
Alexander Shvets (2019), Dive into Design Patterns, Refactoring.Guru
Decorator
Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors.
Structure
Code
from abc import ABC, abstractmethod
class Component(ABC):
@abstractmethod
def operation(self) -> str:
pass
class ConcreteComponent(Component):
def operation(self) -> str:
return "ConcreteComponent"
class Decorator(Component):
def __init__(self, component: Component) -> None:
self.component = component
def operation(self) -> str:
return self.component.operation()
class ConcreteDecoratorA(Decorator):
def operation(self) -> str:
return f"ConcreteDecoratorA({self.component.operation()})"
class ConcreteDecoratorB(Decorator):
def operation(self) -> str:
return f"ConcreteDecoratorB({self.component.operation()})"
def client_code(component: Component) -> None:
# ...
print(f"RESULT: {component.operation()}", end="")
# ...
if __name__ == "__main__":
simple = ConcreteComponent()
decorator1 = ConcreteDecoratorA(simple)
decorator2 = ConcreteDecoratorB(decorator1)
client_code(decorator2)
# RESULT: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))