Junior — Middle
95
¿Puedes dar un ejemplo de la aplicación del patrón decorador en el código?
Empresas donde se preguntó
Respuesta de la IA
sobes.tech AI
Паттерн декоратор позволяет динамически добавлять объектам новые обязанности, оборачивая их в другие объекты-декораторы.
Пример на Python — добавим декоратор для логирования вызова метода:
class Component:
def operation(self):
return "Основная операция"
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("Лог: вызов операции")
result = self._component.operation()
print("Лог: операция завершена")
return result
# Использование
component = Component()
decorated = LoggingDecorator(component)
print(decorated.operation())
Вывод:
Лог: вызов операции
Лог: операция завершена
Основная операция
Таким образом, мы обернули объект Component в LoggingDecorator, добавив функциональность логирования без изменения исходного класса.