Bu yazı Design Patterns/Tasarım Desenleri nedir? başlıklı yazı dizisinin bir parçasıdır.

Bu içerik ağırlıklı olarak refactoring.guru sitesindeki içeriğin tercümesi ve derlenmesinden oluşturulmuştur.

Tüm tasarım desenleri ya da diğer adıyla tasarım kalıplarına yönelik ayrıntılı içeriklere yazının sonundaki bağlantılardan ulaşabilirsiniz.

Composite tasarım deseninin amacı

Composite (Kompozit) nesneleri ağaç yapıları halinde oluşturmanıza ve bu ağacın dalları ile tek tek nesnelermiş gibi çalışmanıza olanak veren bir bir tasarım desenidir.

Sorun

Uygulamanızın ana modeli bir ağaç şeklinde gösterilebiliyorsa composite tasarım desenini kullanmanız işe yarayabilir.

Örnek olara Products (Ürünler) ve Boxes (kutular) şeklinde iki tür nesneniz var diyelim. Bir kutu birden fazla ürün içerebilir, hatta daha küçük kutular da içerebilir. Bu kutuların içinde de ürünler ya da kendilerinden daha küçük kutular olabilir. (ve bu böyle gider)

Bu sınıfları kullanan bir sıralama sistemi yapmaya karar verdiğinizi düşünün. Siparişler herhangi bir paketleme yapılmaya gerek olmayan basit ürünler içerdiği gibi, içi bir çok ürünle dolu kutulardan da oluşabilir. Böyle bir siparişin toplam fiyatını nasıl belirlersiniz?

Composite Tasarım Deseni
Bir sipariş kutular içine paketlenmiş çeşitli ürünlerden oluşabilir ve bu kutularda daha büyük başka kutuların içine koyulmuş olabilirler. Yapıya yukarıdan aşağı bakıldığında bir ağaç görünümü oluşturur.

Direkt bir yaklaşımla tüm kutuları açabilir, bütün ürünlere bakabilir ve toplamı hesaplayabilirsiniz. Bu gerçek dünyada uygulanabilir bir yöntem fakat bir program için bir döngü çalıştırmak kadar basit değildir. Tarayacağınız kutu ve ürünlerin sınıflarını, kaç seviye aşağıya gidileceğini vb. diğer detayları önceden bilmeniz gerekir. Bu kısıtlar direkt yaklaşımı kullanışsız ve bazen imkansız hale getirir.

Çözüm

Composite deseni ürünler ve kutularla çalışırken, fiyatı hesaplaması için bir metod içeren ortak bir arayüz kullanmanızı önerir.

Peki bu metod nasıl çalışıyor? Bir ürün için bu basitçe kendi fiyatını döndürür. Bir kutu kendi içindeki tüm öğelere gidip onlara fiyatlarını sorar (aynı arayüzle) ve toplamı döndürür. Eğer bu öğelerden biri küçük bir kutuysa o da içindekilere fiyatları sorarak toplamı bulacak ve önceki büyük kutuya bu toplamı gönderecektir. Böylece hiç bir kutu daha alt seviyelerde ne olduğunu bilmek zorunda kalmayacaktır.

Kompozit tasarım deseni nedir?
Composite pattern bir çağrıyı bir nesne ağacındaki tüm bileşenler için öz yinelemeli (recursive) olarak çağırabilmenizi sağlar.

Bu metodun en avantajlı tarafı ağaçtaki nesnelerin tam sınıflarını bilmeniz gerekmemesidir. Nesnenin tipinden bağımsız olarak composite arayüzdeki metodu içermesi sizin için yeterlidir. Bir nesne basit bir ürün mü, yoksa karmaşık içerikli bir kutu mu önceden bilmeniz gerekmez. Bir metodu çağırdığınızda daha aşağılara inilmesi gerekiyorsa ilgili nesne bunu kendisi yapacaktır.

Uygulanabilirlik

Ağaç benzeri bir nesne yapısı uyarlamanız gerekiyorsa composite tasarım desenini kullanın.

Composite deseni size ortak bir arayüzü paylaşan iki teel eleman tipi sağlar: basit yapraklar ve kompleks dallar. Bir dalda yapraklar veya başka dallar olabilir. Bu ağaca benzer, iç içe geçmiş öz yinelemeli nesne yapıları oluşturmanıza olanak sağlar.

İstemci kodun basit ve kompleks nesneleri aynı şekilde değerlendirmesini istiyorsanız bu tasarım kalbını kullanın.

Composite tasarım kalıbı ile tanımlanmış tüm elemanlar ortak bir arayüze sahiptir. Bu arayüz sayesinde istemci kod çalıştığı nesnenin asıl sınıfı ile ilgilenmeden işini görebilir.

Diğer tasarım desenleri/kalıpları ile ilişkisi

  • Kompleks Composite ağaçlar oluştururken Builder desenini kullanabilirsiniz. Böylece oluşturma (construction) aşamalarını öz yinelemeli (recursive) olarak belirleyebilirsiniz.
  • Chain of Responsibility (Sorumluluk Zinciri) çoğu zaman Composite ile birlikte kullanılır. Böylece yaprak konumundaki bir bileşen istek aldığında zincir şeklinde tüm üst dallara ileterek ağacın en başına kadar iletilmesini sağlar.
  • Composite ağaçlar arasında dolaşmak için Iterator kullanabilirsiniz.
  • Composite ağacın tamamında bir operasyon çalıştırmak için Visitor kullanabilirsiniz.
  • Hafızadan tasarruf sağlamak için Composite ağacın bazı yaprak düğümlerini Flyweight olarak tanımlayabilirsiniz.
  • Composite ve Decorator desenleri ortak bir yapısal gösterime sahiptirler çünkü her ikiside ucu açık/sonsuz sayıda nesnenin öz yinelemeli (recursive) olarak organize edilmesini sağlar.

    Bir Decorator bir Composite‘e çok benzer fakat Decorator‘ün sadece bir alt bileşeni vardır. İkisi arasındaki önemli fark; Decorator kapsadığı nesneye ek sorumluluklar yüklerken, Composite sadece altındaki nesnelerin sonuçlarını toplar.

    Fakat bu iki desen birlikte de çalışabilir. Composite ağacındaki bir nesnenin davranışını Decorator kullanarak genişletebilirsiniz.
  • Yoğun şekilde Composite ve Decorator kullanan tasarımlar Prototype‘dan da faydalanabilir. Böylece bu kompleks yapıları baştan oluşturmak yerine klonlayabilirsiniz.

Composite Tasarım Deseni Kod Örnekleri

Örnek PHP Kodu

<?php

namespace RefactoringGuru\Composite\Conceptual;

/**
 * The base Component class declares common operations for both simple and
 * complex objects of a composition.
 */
abstract class Component
{
    /**
     * @var Component
     */
    protected $parent;

    /**
     * Optionally, the base Component can declare an interface for setting and
     * accessing a parent of the component in a tree structure. It can also
     * provide some default implementation for these methods.
     */
    public function setParent(Component $parent)
    {
        $this->parent = $parent;
    }

    public function getParent(): Component
    {
        return $this->parent;
    }

    /**
     * In some cases, it would be beneficial to define the child-management
     * operations right in the base Component class. This way, you won't need to
     * expose any concrete component classes to the client code, even during the
     * object tree assembly. The downside is that these methods will be empty
     * for the leaf-level components.
     */
    public function add(Component $component): void { }

    public function remove(Component $component): void { }

    /**
     * You can provide a method that lets the client code figure out whether a
     * component can bear children.
     */
    public function isComposite(): bool
    {
        return false;
    }

    /**
     * The base Component may implement some default behavior or leave it to
     * concrete classes (by declaring the method containing the behavior as
     * "abstract").
     */
    abstract public function operation(): string;
}

/**
 * The Leaf class represents the end objects of a composition. A leaf can't have
 * any children.
 *
 * Usually, it's the Leaf objects that do the actual work, whereas Composite
 * objects only delegate to their sub-components.
 */
class Leaf extends Component
{
    public function operation(): string
    {
        return "Leaf";
    }
}

/**
 * The Composite class represents the complex components that may have children.
 * Usually, the Composite objects delegate the actual work to their children and
 * then "sum-up" the result.
 */
class Composite extends Component
{
    /**
     * @var \SplObjectStorage
     */
    protected $children;

    public function __construct()
    {
        $this->children = new \SplObjectStorage();
    }

    /**
     * A composite object can add or remove other components (both simple or
     * complex) to or from its child list.
     */
    public function add(Component $component): void
    {
        $this->children->attach($component);
        $component->setParent($this);
    }

    public function remove(Component $component): void
    {
        $this->children->detach($component);
        $component->setParent(null);
    }

    public function isComposite(): bool
    {
        return true;
    }

    /**
     * The Composite executes its primary logic in a particular way. It
     * traverses recursively through all its children, collecting and summing
     * their results. Since the composite's children pass these calls to their
     * children and so forth, the whole object tree is traversed as a result.
     */
    public function operation(): string
    {
        $results = [];
        foreach ($this->children as $child) {
            $results[] = $child->operation();
        }

        return "Branch(" . implode("+", $results) . ")";
    }
}

/**
 * The client code works with all of the components via the base interface.
 */
function clientCode(Component $component)
{
    // ...

    echo "RESULT: " . $component->operation();

    // ...
}

/**
 * This way the client code can support the simple leaf components...
 */
$simple = new Leaf();
echo "Client: I've got a simple component:\n";
clientCode($simple);
echo "\n\n";

/**
 * ...as well as the complex composites.
 */
$tree = new Composite();
$branch1 = new Composite();
$branch1->add(new Leaf());
$branch1->add(new Leaf());
$branch2 = new Composite();
$branch2->add(new Leaf());
$tree->add($branch1);
$tree->add($branch2);
echo "Client: Now I've got a composite tree:\n";
clientCode($tree);
echo "\n\n";

/**
 * Thanks to the fact that the child-management operations are declared in the
 * base Component class, the client code can work with any component, simple or
 * complex, without depending on their concrete classes.
 */
function clientCode2(Component $component1, Component $component2)
{
    // ...

    if ($component1->isComposite()) {
        $component1->add($component2);
    }
    echo "RESULT: " . $component1->operation();

    // ...
}

echo "Client: I don't need to check the components classes even when managing the tree:\n";
clientCode2($tree, $simple);

Örnek Python Kodu

from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List


class Component(ABC):
    """
    The base Component class declares common operations for both simple and
    complex objects of a composition.
    """

    @property
    def parent(self) -> Component:
        return self._parent

    @parent.setter
    def parent(self, parent: Component):
        """
        Optionally, the base Component can declare an interface for setting and
        accessing a parent of the component in a tree structure. It can also
        provide some default implementation for these methods.
        """

        self._parent = parent

    """
    In some cases, it would be beneficial to define the child-management
    operations right in the base Component class. This way, you won't need to
    expose any concrete component classes to the client code, even during the
    object tree assembly. The downside is that these methods will be empty for
    the leaf-level components.
    """

    def add(self, component: Component) -> None:
        pass

    def remove(self, component: Component) -> None:
        pass

    def is_composite(self) -> bool:
        """
        You can provide a method that lets the client code figure out whether a
        component can bear children.
        """

        return False

    @abstractmethod
    def operation(self) -> str:
        """
        The base Component may implement some default behavior or leave it to
        concrete classes (by declaring the method containing the behavior as
        "abstract").
        """

        pass


class Leaf(Component):
    """
    The Leaf class represents the end objects of a composition. A leaf can't
    have any children.

    Usually, it's the Leaf objects that do the actual work, whereas Composite
    objects only delegate to their sub-components.
    """

    def operation(self) -> str:
        return "Leaf"


class Composite(Component):
    """
    The Composite class represents the complex components that may have
    children. Usually, the Composite objects delegate the actual work to their
    children and then "sum-up" the result.
    """

    def __init__(self) -> None:
        self._children: List[Component] = []

    """
    A composite object can add or remove other components (both simple or
    complex) to or from its child list.
    """

    def add(self, component: Component) -> None:
        self._children.append(component)
        component.parent = self

    def remove(self, component: Component) -> None:
        self._children.remove(component)
        component.parent = None

    def is_composite(self) -> bool:
        return True

    def operation(self) -> str:
        """
        The Composite executes its primary logic in a particular way. It
        traverses recursively through all its children, collecting and summing
        their results. Since the composite's children pass these calls to their
        children and so forth, the whole object tree is traversed as a result.
        """

        results = []
        for child in self._children:
            results.append(child.operation())
        return f"Branch({'+'.join(results)})"


def client_code(component: Component) -> None:
    """
    The client code works with all of the components via the base interface.
    """

    print(f"RESULT: {component.operation()}", end="")


def client_code2(component1: Component, component2: Component) -> None:
    """
    Thanks to the fact that the child-management operations are declared in the
    base Component class, the client code can work with any component, simple or
    complex, without depending on their concrete classes.
    """

    if component1.is_composite():
        component1.add(component2)

    print(f"RESULT: {component1.operation()}", end="")


if __name__ == "__main__":
    # This way the client code can support the simple leaf components...
    simple = Leaf()
    print("Client: I've got a simple component:")
    client_code(simple)
    print("\n")

    # ...as well as the complex composites.
    tree = Composite()

    branch1 = Composite()
    branch1.add(Leaf())
    branch1.add(Leaf())

    branch2 = Composite()
    branch2.add(Leaf())

    tree.add(branch1)
    tree.add(branch2)

    print("Client: Now I've got a composite tree:")
    client_code(tree)
    print("\n")

    print("Client: I don't need to check the components classes even when managing the tree:")
    client_code2(tree, simple)

Diğer Tasarım Kalıpları/Design Patterns

Yaratımsal Kalıplar (Creational Patterns)

Yapısal Kalıplar (Structural Patterns)

Davranışsal Kalıplar (Behavioral Patterns)