Junior — Middle
In what situations is the Decorator pattern typically used?
sobes.tech AI
Answer from AI
The Decorator pattern is used when you need to dynamically add new responsibilities or behaviors to an object without changing its original code and without creating a large number of subclasses.
Typical use cases:
- Extending the functionality of objects at runtime.
- Adding additional capabilities (e.g., logging, caching, access control) without modifying the base class.
- Ensuring flexible composition of behaviors.
Example in Python:
def decorator(func):
def wrapper(*args, **kwargs):
print("Before calling the function")
result = func(*args, **kwargs)
print("After calling the function")
return result
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
Here, the decorator function adds additional behavior around the call to say_hello without changing its code.