Sobes.tech
Junior — Middle

How are the 'Decorator' design pattern implemented and what is its principle of operation in programming?

sobes.tech AI

Answer from AI

The "Decorator" design pattern allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects without changing the original class code. It is an alternative to inheritance for extending functionality.

Working principle:

  • There is a base interface or abstract class.
  • The original object implements this interface.
  • The decorator contains a reference to an object of the same interface and implements additional behavior by calling methods of the wrapped object.

Example in Python:

class Component:
    def operation(self):
        return "Component"

class Decorator(Component):
    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, objects can be wrapped in multiple decorators, extending their behavior without modifying the original class.