Middle — Middle+
Explain the concept of decorator factory and how it is used in system design.
sobes.tech AI
Answer from AI
A decorator factory is a design pattern that combines the factory method and the decorator pattern. The idea is that the factory creates objects by wrapping them in one or more decorators, adding additional behavior dynamically.
In Python, this can be conveniently implemented using decorator functions and factory functions that return wrapped objects.
Example:
def decorator_factory(extra_behavior):
def decorator(func):
def wrapper(*args, **kwargs):
print(f"Before {func.__name__}")
result = func(*args, **kwargs)
print(extra_behavior)
print(f"After {func.__name__}")
return result
return wrapper
return decorator
# Using the factory to create a decorator with different behaviors
my_decorator = decorator_factory("Additional behavior")
@my_decorator
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
In decorator factory systems, it allows centralized creation of objects with the required set of wrappers, simplifying management of functionality and extensibility.