Sobes.tech
Middle

Proqramlaşdırma kontekstində dekorator (Decorator) nədir və necə istifadə olunur?

sobes.tech Süni İntellekt

AI-dan cavab

Dekorator, strukturlaşdırıcı dizayn naxşidir və obyektlərin strukturunu dəyişdirmədən onlara dinamik olaraq yeni davranışlar və ya vəzifələr əlavə etməyə imkan verir.

Əsas fikirlər:

  • Mövcud obyekti əhatə edir və onun funksionallığını genişləndirir.
  • Əhatə olunan obyektin interfeysini saxlayır və dəyişdirilə bilənliyi təmin edir.
  • Yeni davranış kombinasiyalarını əlavə edərkən sinif hierarxiyalarının çoxalmasının qarşısını alır.

İstifadə:

  1. "İş vaxtı" funksionallığın genişləndirilməsi: Proqramın icrası zamanı obyektin davranışını əlavə etmək və ya dəyişdirmək lazım olduqda istifadə olunur.
  2. Mirasın yerinə: Hər davranış kombinasiyası üçün alt siniflər yaratmaq əvəzinə, dekoratorlar istifadə olunur. Bu daha çevik yanaşmadır.
  3. Davranışların kombinasiyası: Müxtəlif dekoratorlar eyni obyektə fərqli ardıcıllıqla tətbiq oluna bilər və unikal kombinasiyalar yarada bilər.

Python nümunəsi:

# Əsas komponent
class Component:
    def operation(self):
        pass

# Konkret komponent
class ConcreteComponent(Component):
    def operation(self):
        return "ConcreteComponent"

# Əsas dekorator (sarmalayan obyektə istinad saxlayır)
class Decorator(Component):
    def __init__(self, component):
        self._component = component

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

# Konkret dekorator A
class ConcreteDecoratorA(Decorator):
    def operation(self):
        return f"ConcreteDecoratorA({self._component.operation()})"

# Konkret dekorator B
class ConcreteDecoratorB(Decorator):
    def operation(self):
        return f"ConcreteDecoratorB({self._component.operation()})"

# İstifadə
simple = ConcreteComponent()
print(simple.operation())  # ConcreteComponent

decorated_a = ConcreteDecoratorA(simple)
print(decorated_a.operation()) # ConcreteDecoratorA(ConcreteComponent)

decorated_b_a = ConcreteDecoratorB(decorated_a)
print(decorated_b_a.operation()) # ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))

Python-də sintaktik şəkər nümunəsi @:

def my_decorator(func):
    def wrapper():
        print("Funktsiyadan əvvəl")
        func()
        print("Funktsiyadan sonra")
    return wrapper

@my_decorator
def say_hello():
    print("Salam!")

say_hello()
# Nəticə:
# Funktsiyadan əvvəl
# Salam!
# Funktsiyadan sonra