Sobes.tech
Junior — Middle

What is the purpose of the 'decorator' pattern in programming?

sobes.tech AI

Answer from AI

The "decorator" pattern is used for dynamically extending the functionality of an object without modifying its original code. This allows you to "wrap" an object in another decorator object that adds new capabilities while preserving the original interface.

For example, in Python, you can use function decorators to add logging or access control:

def decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@decorator
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("World")

Here, decorator adds additional behavior when calling the function without changing its original code.