Sobes.tech
Junior — Middle

Can you give an example of applying the decorator pattern in code?

sobes.tech AI

Answer from AI

The decorator pattern allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects.

Example in Python — adding a decorator for logging method calls:

class Component:
    def operation(self):
        return "Main operation"

class Decorator:
    def __init__(self, component):
        self._component = component

    def operation(self):
        result = self._component.operation()
        return result

class LoggingDecorator(Decorator):
    def operation(self):
        print("Log: method call")
        result = self._component.operation()
        print("Log: operation completed")
        return result

# Usage
component = Component()
decorated = LoggingDecorator(component)
print(decorated.operation())

Output:

Log: method call
Log: operation completed
Main operation

Thus, we wrapped the Component object in a LoggingDecorator, adding logging functionality without modifying the original class.