CodeBlanks Logo Icon CodeBlanks

Decorator

Decorator desenini öğrenirsin.

Decorator (tasarım deseni)

Decorator tasarım deseni, bir nesneyi sararak davranışını genişletir. Python'un @decorator söz diziminden farklıdır; burada sarmalayıcı bir sınıf, içteki nesneyi tutar ve yöntemleri onun üzerinden çağırır.

class Coffee:
    def cost(self):
        return 10

class MilkDecorator:
    def __init__(self, coffee):
        self._coffee = coffee
    def cost(self):
        return self._coffee.cost() + 2

Decorator, sarmalanan nesneyi değiştirmeden yeni davranış ekler; örneğin içeceke süt, şeker gibi ekler katman katman eklenir.

katmanlı decorator

Decorator'lar katmanlı olabilir; her katman bir öncekini sarar. Bu, dinamik olarak davranış eklemeyi sağlar.

class SugarDecorator:
    def __init__(self, coffee):
        self._coffee = coffee
    def cost(self):
        return self._coffee.cost() + 1

c = SugarDecorator(MilkDecorator(Coffee()))
print(c.cost())  # 10 + 2 + 1 = 13

Bu, alt sınıflama yerine bir alternatiftir; sınıf sayısını artırmadan çok sayıda kombinasyon oluşturursun.

Uygulama Decorator ile kahve maliyeti

class Coffee: tanımla; def cost(self): metodu return 10 yapsın. class MilkDecorator: tanımla; def __init__(self, coffee): metodu self._coffee = coffee yapsın. def cost(self): metodu return self._coffee.cost() + 2 yapsın. c = MilkDecorator(Coffee()) ile örnek oluştur. print(c.cost()) ile maliyeti yazdır.

Başlangıç kodu

main.py
# Coffee sınıfını tanımla (cost = 10)
# MilkDecorator sınıfını tanımla (iç nesneyi sakla, cost + 2)
# bir Coffee örneğini MilkDecorator ile sar
# maliyeti yazdır

Örnek çözüm

main.py
class Coffee:
    def cost(self):
        return 10

class MilkDecorator:
    def __init__(self, coffee):
        self._coffee = coffee
    def cost(self):
        return self._coffee.cost() + 2

c = MilkDecorator(Coffee())
print(c.cost())

Beklenen çıktı

12

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 Decorator __init__ gövdesini tamamla

Soru
class MilkDecorator:
    def __init__(self, coffee):
        self.____ = coffee
Cevap
class MilkDecorator:
    def __init__(self, coffee):
        self._coffee = coffee

Açıklama: self._coffee = coffee ile iç nesne saklanır.

2 Decorator deseninde MilkDecorator.cost() ne döndürür?

  • Hata fırlatır
  • Yalnızca 2
  • Yalnızca iç nesnenin cost
  • İç nesnenin cost + 2 Doğru cevap

Açıklama: self._coffee.cost() + 2 ile iç nesne çağrılır ve eklenir.

3 Decorator kavramlarını eşleştir

Kavram Anlamı
MilkDecorator Sarmalayıcıdır
self._coffee İç nesnedir
cost() + 2 Davranış ekler
katmanlama Dinamik genişletme

İleri seviye bölümündeki tüm dersler