Junior — Middle
85
Kun je een voorbeeld geven van het toepassen van het decorator-patroon in de code?
Bedrijven waar gevraagd werd
Antwoord van AI
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, добавив функциональность логирования без изменения исходного класса.