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
- Encapsulate families: Group related objects (e.g., UI components for Windows vs macOS).
- Consistency: Ensure products from the same factory are compatible.
- Loose Coupling: Client depends on abstractions, not concrete implementations.
Structure
- Abstract Factory: Interface with methods for creating each product in the family.
- Concrete Factory: Implements methods to return concrete products.
- Abstract Product: Interface for each product type.
- Concrete Product: Specific implementations.
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
- When your system needs to create families of related objects (e.g., UI themes, database drivers).
- When you want to ensure compatibility between created objects.
- When adding new product families should be easy (just add new concrete factory).
Summary: Abstract Factory lets you create entire families of compatible objects through a common interface, keeping client code independent of concrete classes.