The Abstract Factory pattern provides a way to create families of related or dependent objects without specifying their exact classes. It helps make your code more flexible and easier to extend by grouping object creation into a unified interface.
In some applications, you need to support multiple sets of objects that should work together—such as GUI components for different platforms like Windows or macOS. Without this pattern, you might end up using if-else
or switch
statements scattered throughout your code to choose the right object. Abstract Factory centralizes this logic, making it easier to manage and extend, especially when supporting new platforms or styles.
Use this pattern when:
Avoid this pattern if:
The pattern includes four key parts:
Button
, Checkbox
).WindowsButton
, MacButton
).Think of a supermarket that adjusts its offerings based on your dietary choice. If you choose “vegan,” you’re directed to vegan-friendly versions of fruits, dairy alternatives, and baked goods—all tailored to that preference. Similarly, an abstract factory supplies a consistent set of products from the same family.
Here’s a basic Python example:
from abc import ABC, abstractmethod
# Abstract Product
class ProductA(ABC):
@abstractmethod
def do_something(self) -> str:
pass
# Concrete Products
class ConcreteProductA1(ProductA):
def do_something(self) -> str:
return "Implementation of Product A1"
class ConcreteProductA2(ProductA):
def do_something(self) -> str:
return "Implementation of Product A2"
In this example:
ProductA
is the abstract product interface.ConcreteProductA1
and ConcreteProductA2
are different versions tailored to specific themes or platforms.A full implementation would also include a factory interface and one or more factory classes to handle product creation.
See the complete implementation in Python here: Abstract Factory on GitHub