Junior — Middle
What is the main purpose of using the Decorator pattern and what are its advantages?
sobes.tech AI
Answer from AI
The Decorator pattern allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects without changing the original code. This is especially useful when you need to extend functionality without creating numerous subclasses.
Advantages:
- Flexibility: decorators can be combined for different effects.
- Separation of concerns: each decorator is responsible for its own function.
- Avoids explosive growth of subclasses.
Example in Python:
class Component:
def operation(self):
return "Main operation"
class Decorator(Component):
def __init__(self, component):
self._component = component
def operation(self):
return f"Decor({self._component.operation()})"
component = Component()
decorated = Decorator(component)
print(decorated.operation()) # Outputs: Decor(Main operation)