Middle
What is a decorator?
sobes.tech AI
Answer from AI
Decorator is a design pattern that allows adding new behavior to an object dynamically without changing its structure.
Main characteristics:
- Flexibility: Allows adding or removing functionality of objects at runtime.
- Independence: New functionality can be added independently of the main class.
- Use of composition: The decorator contains a reference to the decorated object and forwards requests to it, adding some logic before or after execution.
Applications:
- Logging
- Access control (authentication/authorization)
- Adding metadata
- Changing method behavior
Example in Python:
# Simple function for decoration
def my_function():
return "Hello"
# Decorator
def simple_decorator(func):
def wrapper():
print("Before function call")
result = func()
print("After function call")
return result
return wrapper
# Applying the decorator
@simple_decorator
def decorated_function():
return "World"
# Calling the decorated function
# decorated_function() would output:
# Before function call
# After function call
# and return "World"