Junior — Middle
Can you explain the concept of the Decorator pattern and how it is used to extend the functionality of objects?
sobes.tech AI
Answer from AI
The Decorator pattern allows dynamically extending the functionality of an object without modifying its original code. This is achieved by wrapping the object in another decorator object that implements the same interface and adds new functionality.
In Python, this is often implemented through classes that accept an object and override methods, calling the original methods and adding additional behavior.
Example:
class Component:
def operation(self):
return "Component"
class Decorator:
def __init__(self, component):
self._component = component
def operation(self):
return f"Decorator({self._component.operation()})"
# Usage
component = Component()
decorated = Decorator(component)
print(decorated.operation()) # Outputs: Decorator(Component)
This way, functionality such as logging, caching, or validation can be added without changing the original class.