Sobes.tech
Junior — Middle

What is the Decorator pattern and what is its main function in programming?

sobes.tech AI

Answer from AI

Decorator pattern is a structural design pattern that allows dynamically adding responsibilities to objects by wrapping them in decorator objects. Its main purpose is to extend the behavior of objects without modifying their original code, while maintaining the same interface.

In Python, it is often used as a function decorator, which takes a function and returns a new function with additional behavior.

Simple decorator example in Python:

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()

Here, say_hello is wrapped in wrapper, which adds extra functionality before and after the original function call.