Abstract Factory Tasarım Deseni Nedir?

Sayfayı kopyala
💡 Özet (TL;DR):
- Amacı: Birbiriyle ilişkili veya bağımlı nesne ailelerini, onların somut sınıflarını (concrete classes) belirtmeden oluşturmak için bir arayüz (interface) sağlayan oluşumsal (creational) bir tasarım desenidir.
- Çözdüğü Sorun: Kodun, ürün varyasyonlarının (örneğin Modern, Viktorya tarzı) somut sınıflarına sıkı sıkıya bağlanmasını önler ve ürünlerin birbiriyle uyumlu üretilmesini garanti eder.
- Yöntem: Her ürün varyasyonu için ayrı bir fabrika sınıfı (Concrete Factory) tanımlanır. İstemci kod, bu fabrikalarla ortak bir soyut fabrika arayüzü (Abstract Factory) üzerinden çalışır.
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 Deseninin Amacı
Türkçeye birebir çevrildiğinde "soyut fabrika" gibi anlamsız bir ifadeye dönüşen Abstract Factory, birbiriyle ilişkili sınıfları (class) ve metotların içeriğini belirtmeden nesneler oluşturmayı sağlar.
Sorun
Bir mobilya mağazası simülatörü oluşturacağınızı düşünün. Kodunuz aşağıdakileri ifade eden sınıflar içermelidir:
- İlgili ürünlerden oluşan bir ürün ailesi: Örneğin
Koltuk+Kanepe+Sehpa - Bu ailenin çeşitli varyasyonları: Örneğin
Sandalye+Koltuk+SehpaürünlerininModern+Viktorya (Victorian)+Art Decogibi varyasyonları.

Ürün aileleri ve varyantları.
Oluşturacağınız mobilyaların bir şekilde ürün ailesinin diğer üyeleriyle eşleşmesi gerekir. Müşteriler, birbiriyle uyumsuz ürünlerle karşılaştığında hayal kırıklığına uğrayacaktır.

Modern görünümlü bir kanepe, Viktorya tarzı koltuklarla pek hoş görünmez.
Yeni ürün aileleri veya ürünler eklendiğinde mevcut kodunuzu tamamen değiştirmek de istemezsiniz. Mobilya üreticilerinin modellerini sürekli güncelledikleri düşünüldüğünde, bu durum yazılım geliştirme sürecinde sıkça karşılaşacağınız bir problemdir.
Çözüm
Abstract Factory tasarım kalıbının ilk önerdiği çözüm, ürün ailesinin her bir ürün tipi için (koltuk, kanepe, sehpa gibi) ayrı bir arayüz (interface) oluşturmanızdır. Akabinde tüm varyantların bu arayüzü temel almasını sağlayabilirsiniz. Örneğin, tüm koltuk varyasyonlarında Koltuk arayüzünü, tüm sehpa varyasyonlarında ise Sehpa arayüzünü esas alabilirsiniz.

Tüm varyantlar tek bir sınıf hiyerarşisine taşınmalıdır.
Bir sonraki adım, ürün ailesine ait olan ürünleri oluşturmak için gereken tüm metotları 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 metotlar, yukarıda tanımladığımız (koltuk, kanepe, sehpa) arayüz biçimlerinde soyut (abstract) ürünler döndürmelidir.

Her ürün varyantına özel Concrete Factory'ler
Ürün varyantları için bu Abstract Factory arayüzünü esas alan ayrı ayrı fabrika sınıfları (Factory Classes) oluşturmalıyız. Fabrika sınıfı, ilgili tipteki ürünü geri döndüren özel bir sınıftır. Örneğin ModernFurnitureFactory sınıfı sadece ModernChair, ModernSofa ve ModernCoffeeTable nesnelerini döndürebilir.
İstemci kod, fabrikalar ve ürünlerle çalışırken her zaman ilgili soyut arayüzleri (interfaces) kullanmalıdır. Bu sayede, istemci koda parametre olarak gönderdiğiniz fabrika sınıfını ve ürün varyantını, asıl koda dokunmadan kolayca değiştirebilirsiniz.

Müşteri fabrikanın içinde dönen işleri bilmek zorunda olmadan sadece ürününü almalıdır.
Farz edelim istemci geldi ve fabrika sınıfımızdan bir koltuk istedi. İstemci, fabrikanın alt sınıfı veya arka planda nasıl bir koltuk üretildiği ile ilgilenmez. Abstract Factory arayüzüne uygun bir fabrika nesnesi kendisine verildiyse onun için yeterlidir. Böylece modern koltuk mu gelmiş, yoksa Viktorya tarzı mı gelmiş bunu umursamadan, üzerine oturmak için bir sitOn metodu içeren Chair arayüzüne uygun bir koltuk nesnesi alacağı garantidir. Dönen koltuğun varyantı neyse, gelecek kanepe ve sehpa gibi diğer ürünlerin varyantının da o olacağı bu sayede garanti altına alınmış olur.
Abstract Factory ve Factory Method Desenleri Arasındaki Fark
| Özellik | Factory Method | Abstract Factory |
|---|---|---|
| Temel Odak | Tek bir ürünün oluşturulmasını alt sınıflara delege eder (Metot seviyesinde). | Birbiriyle ilişkili ürün ailelerinin oluşturulmasını sağlar (Sınıf seviyesinde). |
| Uygulama Yöntemi | Kalıtım (Inheritance) esaslıdır; alt sınıflar metodu ezerek nesneyi oluşturur. | Kompozisyon (Composition) esaslıdır; fabrika nesnesi bağlama enjekte edilir. |
| Gereksinim | Tek bir ürün üretilmek istendiğinde tercih edilir. | Birbiriyle uyumlu çalışması gereken birden fazla ürün grubu (örneğin Koltuk + Masa + Sehpa) olduğunda tercih edilir. |
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 somut içeriklerine bağımlı olmak istemediğiniz durumlarda size yardımcı olurlar. Bu sınıfların ne olacağı başlangıçta 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 soyut bir arayüz sunarlar. Kodunuz nesneleri bu arayüz üzerinden oluşturduğu sürece, üretilen diğer ürünlerle uyuşmayan, uyumsuz bir ürün varyasyonu üretilmesini engellemiş olursunuz.
İyi tasarlanmış bir sistemde her sınıfın tek bir sorumluluğu olmalıdır (Single Responsibility Principle). Eğer birden fazla işlevi idare eden karmaşık bir sınıfınız varsa, bunun fabrika metotlarını bağımsız fabrika sınıflarına (Factory Classes) veya tam bir Abstract Factory uygulamasına dönüştürmeniz faydalı olacaktır. Eğer kodunuzda bir Factory Method'a ihtiyaç duyuyorsanız, şimdi veya gelecekte benzer başka fabrika metotlarına ihtiyaç duyup duymayacağınızı değerlendirerek Abstract Factory yapısına geçişi planlayabilirsiniz.
Diğer Tasarım Desenleri ile İlişkisi
- Birçok tasarım süreci Factory Method kullanılarak başlar (daha az karmaşık olduğu ve alt sınıflarla özelleştirilebildiği için) ve ihtiyaçlar arttıkça Abstract Factory yapısına doğru evrilir.
- Builder deseni kompleks nesnelerin adım adım oluşturulmasını sağlar. Abstract Factory ise ilgili nesne ailelerini tek seferde oluşturmak için idealdir. Abstract Factory ürünü hemen döndürürken, Builder ürünü istemciye teslim etmeden önce çeşitli yapılandırma adımları çalıştırmanıza izin verir.
- Abstract Factory sınıfları genel olarak bir dizi Factory Method'dan oluşur, fakat bu sınıfları oluşturmak için Prototype kalıbını da tercih edebilirsiniz.
- Abstract Factory kalıbını Bridge ile birlikte kullanabilirsiniz. Bu yöntem, Bridge üzerinde tanımlanan bazı soyutlamaların sadece belirli platformlar veya uygulamalarla çalışması gerektiğinde oldukça faydalıdır. Abstract Factory deseni bu ilişkileri kapsülleyerek karmaşıklığı ortadan kaldırır.
- Abstract Factory sınıfları genellikle Singleton olarak tasarlanır.
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="")
"""
The client code can work with any concrete factory class.
"""
if __name__ == "__main__":
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
Oluşumsal Kalıplar (Creational Patterns)
Factory Method, Abstract Factory, Builder, Prototype, Singleton
Yapısal Kalıplar (Structural Patterns)
Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy
Davranışsal Kalıplar (Behavioral Patterns)
Chain of Responsibility, Command, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor
