Abstract Factory Method Pattern

The Abstract Factory is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. It extends the Factory Method by allowing creation of multiple product families through a single factory interface.

Key Principles

Structure

Python Example: GUI Factory (Windows vs macOS Themes)

from abc import ABC, abstractmethod

# Abstract Products
class Button(ABC):
    @abstractmethod
    def render(self) -> str:
        pass

class Checkbox(ABC):
    @abstractmethod
    def check(self) -> str:
        pass

# Concrete Products - Windows Style
class WindowsButton(Button):
    def render(self) -> str:
        return "Rendering Windows button"

class WindowsCheckbox(Checkbox):
    def check(self) -> str:
        return "Checking Windows checkbox"

# Concrete Products - macOS Style
class MacButton(Button):
    def render(self) -> str:
        return "Rendering macOS button"

class MacCheckbox(Checkbox):
    def check(self) -> str:
        return "Checking macOS checkbox"

# Abstract Factory
class GUIFactory(ABC):
    @abstractmethod
    def create_button(self) -> Button:
        pass

    @abstractmethod
    def create_checkbox(self) -> Checkbox:
        pass

# Concrete Factories
class WindowsFactory(GUIFactory):
    def create_button(self) -> Button:
        return WindowsButton()

    def create_checkbox(self) -> Checkbox:
        return WindowsCheckbox()

class MacFactory(GUIFactory):
    def create_button(self) -> Button:
        return MacButton()

    def create_checkbox(self) -> Checkbox:
        return MacCheckbox()

# Client Code
def create_ui(factory: GUIFactory):
    button = factory.create_button()
    checkbox = factory.create_checkbox()
    print(button.render())
    print(checkbox.check())

# Usage
if __name__ == "__main__":
    print("Windows UI:")
    create_ui(WindowsFactory())

    print("\nmacOS UI:")
    create_ui(MacFactory())

Output:

Windows UI:
Rendering Windows button
Checking Windows checkbox

macOS UI:
Rendering macOS button
Checking macOS checkbox

When to Use Abstract Factory

Summary: Abstract Factory lets you create entire families of compatible objects through a common interface, keeping client code independent of concrete classes.