Middle
What is a decorator in the context of programming and how is it used?
sobes.tech AI
Answer from AI
Decorator is a structural design pattern that allows adding new behavior or responsibilities to objects dynamically without modifying their structure.
Main ideas:
- Wraps an existing object, extending its functionality.
- Preserves the interface of the wrapped object, ensuring interchangeability.
- Avoids class hierarchy proliferation when adding new behavior combinations.
Usage:
- Extending functionality "on the fly": Used when there's a need to add or change an object's behavior during runtime.
- Alternative to inheritance: Instead of creating subclasses for each behavior combination, decorators are used. This is a more flexible approach.
- Combining behaviors: Different decorators can be applied to the same object in various orders, creating unique combinations.
Example in Python:
# Base component
class Component:
def operation(self):
pass
# Concrete component
class ConcreteComponent(Component):
def operation(self):
return "ConcreteComponent"
# Base decorator (holds a reference to the wrapped object)
class Decorator(Component):
def __init__(self, component):
self._component = component
def operation(self):
return self._component.operation()
# Concrete decorator A
class ConcreteDecoratorA(Decorator):
def operation(self):
return f"ConcreteDecoratorA({self._component.operation()})"
# Concrete decorator B
class ConcreteDecoratorB(Decorator):
def operation(self):
return f"ConcreteDecoratorB({self._component.operation()})"
# Usage
simple = ConcreteComponent()
print(simple.operation()) # ConcreteComponent
decorated_a = ConcreteDecoratorA(simple)
print(decorated_a.operation()) # ConcreteDecoratorA(ConcreteComponent)
decorated_b_a = ConcreteDecoratorB(decorated_a)
print(decorated_b_a.operation()) # ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))
Example in Python as syntactic sugar @:
def my_decorator(func):
def wrapper():
print("Before the function")
func()
print("After the function")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Output:
# Before the function
# Hello!
# After the function