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.

Abstract Factory Tasarım Deseni Amacı

Türkçe’ye birebir çevirinde soyut fabrika gibi anlamsız bir ifadeye dönüşen Abstract Factory birbiri ile ilişki classları (sınıf), methodların içeriğini belirlemeden oluşturmayı sağlıyor.

Sorun

Bir mobilya mağazası simülatörü oluşturacağınızı düşünün. Kodunuz aşağıdakileri ifade eden classlar içermelidir:

  1. İlgili ürünlerden oluşan bir ürün ailesi. Örneğin Koltuk + Kanape + Sehpa
  2. Bu ailenin çeşitli varyasyonları. Örneğin Sandalye + Koltuk + Sehpa ürünlerinin Modern + Victorian + ArtDeco gibi varyasyonları
Product families and their variants.
Ürün aileleri ve varyantları.

Oluşturacağınız mobilyaların bir şekilde ailenin diğer ürünleri ile eşleşmesi gerekir. Müşteriler birbiri ile ilgisiz ürünlerle karşılaştırsa mutsuz olacaktır.

Modern görünümlü bir kanepe, victorian tarzda koltuklarla pek hoş görünmez.

Yeni ürün aileleri veya ürünler eklendiğinde kodunuzu tamamen değiştirmek de istemezsiniz. Mobilya üreticilerinin modellerini sürekli değiştirdikleri düşünüldüğünde bu sık karşılaşacağınız bir durum.

Çözüm

Abstract Factory tasarım kalbının ilk önerdiği ailenin her ürün tipi için (koltuk, kanepe, sehpa gibi) ayrı bir arayüz (interface) oluşturmanız. Akabinde tüm varyantların bu interface’i esas almasını sağlayabilirsiniz. Örneğin tüm koltuk varyantlarında koltuk arayüzünü (interface), tüm sehpa varyantlarında sehpa arayüzünü esas alabilirsiniz vb.

The Chairs class hierarchy
Tüm vayantlar tek bir class hierarşisine taşınmalıdır.

Bir sonraki adım ürün ailesine ait olan ürünleri oluşturmak için gereken tüm methodları içeren bir arayüz yani Abstract Factory Interface’ini tanımlamaktır. Örneğin createChair (koltuk oluştur), createSofa (kanepe oluştur), createCoffeeTable (sehpa oluştur) gibi. Bu metodlar yukarıda tanımadığımız (koltuk, kanepe, sehpa) arayüz (interface) biçimlerinde abstract özellikte ürünler döndürmelidir.

The _Factories_ class hierarchy
Her ürün varyantına özel Concrete Factory’ler

Ürün varyantları için bu Abstract Factory arayüzünü esas alan ayrı ayrı Factory Class’ları oluşturmalıyız. Factory Class, ilgili tipteki ürünü geri döndüren özel bir class türüdür. Örneğin ModernFurnitureFactory class’ı sadece ModernChair, ModernSofa ve ModernCoffeeTable nesnelerini döndürebilir.

İstemci kod, factory’ler ve ürünlerle çalışırken ilgili abstract interface’i kullanmalıdır. Bu size istemci kod’a pasladığınız factory sınıfı ve ürün varyantını asıl koda dokunmadan kolayca değiştirme olanağı sağlar.

Müşteri fabrikanın içinde dönen işleri bilmek zorunda olmadan sadece ürününü almalıdır.

Farzedelim istemci geldi ve factory class’ımızdan koltuk istedi. İstemci Factory’nin sınıfı veya nasıl bir sandalye getireceği ile ilgilenmez. Abstract Factory’e uygun bir Factory Class’ı kendisine verildiyse onun için yeterlidir. Böylece modern sandalye mi gelmiş, victorian mı gelmiş bunu umursamadan üzerine oturmak için bir sitOn metodu içeren Chair Interface’ine uygun bir sandalye geleceği kesindir. Dönen koltuğun varyantı neyse gelecek kanepe ve sehpa gibi diğer ürünlerin varyantının da bu olacağı da aynı şekilde garantilenmiş olur.

Uygulanabilirlik

Abstract Factory’ler kodunuzun ilişkili ürünler içeren ürün aileleri ile çalışması gerektiği, fakat bu sınıfların içeriğine bağlı olmak istemediğiniz durumlarda size yardımcı olurlar. Bu sınıfların ne olacağı belirsiz olabilir veya belli olsa bile gelecekte programınızı daha kolay genişletmek isteyebilirsiniz.

Abstract Factory’ler ürün ailesinin üyelerini oluşturabileceğiniz bir arayüz sağlarlar. Kodunuzun nesneleri bu arayüzle oluşturduğu sürece kodunuzun ürettiği diğer ürünlerle uyuşmayan bir varyant üretmediğinizden emin olabilirsiniz.

İyi tasarlanmış bir sistemde her class’ın belirli bir görevi olmalıdır. Eğer birden fazla işlevi idare eden bir classınız varsa bunun factory method’larını bağımsız factory class’larına veya tam bir Abstract Factory uygulamasına dönüştürmeniz iyi olabilir. Eğer kodunuzda bir Factory Method’a ihtiyacınız varsa, şimdi veya gelecekte benzer başka Factory Method’lara ihtiyacınız olabilir mi düşünüp geleceğe dönük olarak bir Abstract Factory oluşturmayı da düşünebilirsiniz.

Diğer tasarım desenleri ile ilişkisi

  • Bir çok tasarım Factory Method kullanılarak başlar (çok karmaşık olmadığı ve alt sınıflarla özelleştirilebildiği için), bunlardan bazıları Abstract Factory’e türüne evrimleşebilir.
  • Builder deseni kompleks nesnelerin adım adım oluşturulmasını sağlar. Abstract Factory ilgili nesne aileleri oluşturmak için idealdir. Abstract Factory ürünü hemen döndürürken Builder ürünü getirmeden önce bazı ön oluşturma aşamaları çalıştırmanıza izin verir.
  • Abstract Factory class’ları genel olarak bir takım Factory Method’lardan oluşurlar, fakat bu classları oluşturmak için Prototype kalbını da seçebilirsiniz.
  • Abstract Factory kalbını Bridge ile birlikte kullanabilirsiniz. Bu yöntem Bridge’de tanımlanan bazı soyutlamaların (abstract) sadece belirli uygulamalarda kullanılması durumunda işe yarayabilir. Bu durumda Abstract Factory deseni bu ilişkileri özetleyerek karmaşıklığı ortadan kaldırır.
  • Abstract Factory deseni Singleton olarak uyarlanabilir.

Abstract Factory Kod Örnekleri

Örnek PHP Kodu

<?php

namespace RefactoringGuru\AbstractFactory\Conceptual;

/**
 * The Abstract Factory interface declares a set of methods that return
 * different abstract products. These products are called a family and are
 * related by a high-level theme or concept. Products of one family are usually
 * able to collaborate among themselves. A family of products may have several
 * variants, but the products of one variant are incompatible with products of
 * another.
 */
interface AbstractFactory
{
    public function createProductA(): AbstractProductA;

    public function createProductB(): AbstractProductB;
}

/**
 * Concrete Factories produce a family of products that belong to a single
 * variant. The factory guarantees that resulting products are compatible. Note
 * that signatures of the Concrete Factory's methods return an abstract product,
 * while inside the method a concrete product is instantiated.
 */
class ConcreteFactory1 implements AbstractFactory
{
    public function createProductA(): AbstractProductA
    {
        return new ConcreteProductA1();
    }

    public function createProductB(): AbstractProductB
    {
        return new ConcreteProductB1();
    }
}

/**
 * Each Concrete Factory has a corresponding product variant.
 */
class ConcreteFactory2 implements AbstractFactory
{
    public function createProductA(): AbstractProductA
    {
        return new ConcreteProductA2();
    }

    public function createProductB(): AbstractProductB
    {
        return new ConcreteProductB2();
    }
}

/**
 * Each distinct product of a product family should have a base interface. All
 * variants of the product must implement this interface.
 */
interface AbstractProductA
{
    public function usefulFunctionA(): string;
}

/**
 * Concrete Products are created by corresponding Concrete Factories.
 */
class ConcreteProductA1 implements AbstractProductA
{
    public function usefulFunctionA(): string
    {
        return "The result of the product A1.";
    }
}

class ConcreteProductA2 implements AbstractProductA
{
    public function usefulFunctionA(): string
    {
        return "The result of the product A2.";
    }
}

/**
 * Here's the the base interface of another product. All products can interact
 * with each other, but proper interaction is possible only between products of
 * the same concrete variant.
 */
interface AbstractProductB
{
    /**
     * Product B is able to do its own thing...
     */
    public function usefulFunctionB(): string;

    /**
     * ...but it also can collaborate with the ProductA.
     *
     * The Abstract Factory makes sure that all products it creates are of the
     * same variant and thus, compatible.
     */
    public function anotherUsefulFunctionB(AbstractProductA $collaborator): string;
}

/**
 * Concrete Products are created by corresponding Concrete Factories.
 */
class ConcreteProductB1 implements AbstractProductB
{
    public function usefulFunctionB(): string
    {
        return "The result of the product B1.";
    }

    /**
     * The variant, Product B1, is only able to work correctly with the variant,
     * Product A1. Nevertheless, it accepts any instance of AbstractProductA as
     * an argument.
     */
    public function anotherUsefulFunctionB(AbstractProductA $collaborator): string
    {
        $result = $collaborator->usefulFunctionA();

        return "The result of the B1 collaborating with the ({$result})";
    }
}

class ConcreteProductB2 implements AbstractProductB
{
    public function usefulFunctionB(): string
    {
        return "The result of the product B2.";
    }

    /**
     * The variant, Product B2, is only able to work correctly with the variant,
     * Product A2. Nevertheless, it accepts any instance of AbstractProductA as
     * an argument.
     */
    public function anotherUsefulFunctionB(AbstractProductA $collaborator): string
    {
        $result = $collaborator->usefulFunctionA();

        return "The result of the B2 collaborating with the ({$result})";
    }
}

/**
 * The client code works with factories and products only through abstract
 * types: AbstractFactory and AbstractProduct. This lets you pass any factory or
 * product subclass to the client code without breaking it.
 */
function clientCode(AbstractFactory $factory)
{
    $productA = $factory->createProductA();
    $productB = $factory->createProductB();

    echo $productB->usefulFunctionB() . "\n";
    echo $productB->anotherUsefulFunctionB($productA) . "\n";
}

/**
 * The client code can work with any concrete factory class.
 */
echo "Client: Testing client code with the first factory type:\n";
clientCode(new ConcreteFactory1());

echo "\n";

echo "Client: Testing the same client code with the second factory type:\n";
clientCode(new ConcreteFactory2());

Örnek Python Kodu

from __future__ import annotations
from abc import ABC, abstractmethod


class AbstractFactory(ABC):
    """
    The Abstract Factory interface declares a set of methods that return
    different abstract products. These products are called a family and are
    related by a high-level theme or concept. Products of one family are usually
    able to collaborate among themselves. A family of products may have several
    variants, but the products of one variant are incompatible with products of
    another.
    """
    @abstractmethod
    def create_product_a(self) -> AbstractProductA:
        pass

    @abstractmethod
    def create_product_b(self) -> AbstractProductB:
        pass


class ConcreteFactory1(AbstractFactory):
    """
    Concrete Factories produce a family of products that belong to a single
    variant. The factory guarantees that resulting products are compatible. Note
    that signatures of the Concrete Factory's methods return an abstract
    product, while inside the method a concrete product is instantiated.
    """

    def create_product_a(self) -> AbstractProductA:
        return ConcreteProductA1()

    def create_product_b(self) -> AbstractProductB:
        return ConcreteProductB1()


class ConcreteFactory2(AbstractFactory):
    """
    Each Concrete Factory has a corresponding product variant.
    """

    def create_product_a(self) -> AbstractProductA:
        return ConcreteProductA2()

    def create_product_b(self) -> AbstractProductB:
        return ConcreteProductB2()


class AbstractProductA(ABC):
    """
    Each distinct product of a product family should have a base interface. All
    variants of the product must implement this interface.
    """

    @abstractmethod
    def useful_function_a(self) -> str:
        pass


"""
Concrete Products are created by corresponding Concrete Factories.
"""


class ConcreteProductA1(AbstractProductA):
    def useful_function_a(self) -> str:
        return "The result of the product A1."


class ConcreteProductA2(AbstractProductA):
    def useful_function_a(self) -> str:
        return "The result of the product A2."


class AbstractProductB(ABC):
    """
    Here's the the base interface of another product. All products can interact
    with each other, but proper interaction is possible only between products of
    the same concrete variant.
    """
    @abstractmethod
    def useful_function_b(self) -> None:
        """
        Product B is able to do its own thing...
        """
        pass

    @abstractmethod
    def another_useful_function_b(self, collaborator: AbstractProductA) -> None:
        """
        ...but it also can collaborate with the ProductA.

        The Abstract Factory makes sure that all products it creates are of the
        same variant and thus, compatible.
        """
        pass


"""
Concrete Products are created by corresponding Concrete Factories.
"""


class ConcreteProductB1(AbstractProductB):
    def useful_function_b(self) -> str:
        return "The result of the product B1."

    """
    The variant, Product B1, is only able to work correctly with the variant,
    Product A1. Nevertheless, it accepts any instance of AbstractProductA as an
    argument.
    """

    def another_useful_function_b(self, collaborator: AbstractProductA) -> str:
        result = collaborator.useful_function_a()
        return f"The result of the B1 collaborating with the ({result})"


class ConcreteProductB2(AbstractProductB):
    def useful_function_b(self) -> str:
        return "The result of the product B2."

    def another_useful_function_b(self, collaborator: AbstractProductA):
        """
        The variant, Product B2, is only able to work correctly with the
        variant, Product A2. Nevertheless, it accepts any instance of
        AbstractProductA as an argument.
        """
        result = collaborator.useful_function_a()
        return f"The result of the B2 collaborating with the ({result})"


def client_code(factory: AbstractFactory) -> None:
    """
    The client code works with factories and products only through abstract
    types: AbstractFactory and AbstractProduct. This lets you pass any factory
    or product subclass to the client code without breaking it.
    """
    product_a = factory.create_product_a()
    product_b = factory.create_product_b()

    print(f"{product_b.useful_function_b()}")
    print(f"{product_b.another_useful_function_b(product_a)}", end="")


if __name__ == "__main__":
    """
    The client code can work with any concrete factory class.
    """
    print("Client: Testing client code with the first factory type:")
    client_code(ConcreteFactory1())

    print("\n")

    print("Client: Testing the same client code with the second factory type:")
    client_code(ConcreteFactory2())

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)