Sobes.tech
Junior — Middle

Is it possible to create a class that extends the functionality of another class using the decorator pattern?

sobes.tech AI

Answer from AI

Yes, the decorator pattern allows extending the functionality of an existing class without modifying its code by wrapping an object of that class in another decorator object. In Python, this is often implemented through a class that takes an object of the base class and overrides the necessary methods, adding new 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)

Thus, the decorator class extends the functionality of the base class without inheriting from it directly, but by using composition.