What Is the Abstract Factory Pattern?
The Abstract Factory Pattern is a creational design pattern that lets you produce families of related objects without specifying their concrete classes. It provides an interface for creating a group of related objects (factories), but leaves the actual product instantiation to sub-classes.
This pattern is ideal when:
- You want to enforce consistency among products.
- You need to switch out entire object families at runtime.
- Your code should not depend on the concrete classes of the objects being created.
Real-World Analogy
Think of a furniture showroom with different styles—Modern, Victorian, Art Deco. You don’t mix a Victorian chair with a Modern table, right? Each style comes with its own matching set of products, and the showroom can swap the entire set in and out effortlessly. That’s abstract factory in action.
Python Code Example
Common Interfaces
class Chair:
def sit(self):
raise NotImplementedError()
class Table:
def dine(self):
raise NotImplementedError()
Concrete Products
class ModernChair(Chair):
def sit(self):
print("Sitting on a modern chair.")
class VictorianChair(Chair):
def sit(self):
print("Sitting on a Victorian chair.")
class ModernTable(Table):
def dine(self):
print("Dining on a modern table.")
class VictorianTable(Table):
def dine(self):
print("Dining on a Victorian table.")
Abstract Factory Interface
class FurnitureFactory:
def create_chair(self):
raise NotImplementedError()
def create_table(self):
raise NotImplementedError()
Concrete Factories
class ModernFurnitureFactory(FurnitureFactory):
def create_chair(self):
return ModernChair()
def create_table(self):
return ModernTable()
class VictorianFurnitureFactory(FurnitureFactory):
def create_chair(self):
return VictorianChair()
def create_table(self):
return VictorianTable()
Client Code
def create_room(factory: FurnitureFactory):
chair = factory.create_chair()
table = factory.create_table()
chair.sit()
table.dine()
# Using Modern Furniture
modern_factory = ModernFurnitureFactory()
create_room(modern_factory)
# Using Victorian Furniture
victorian_factory = VictorianFurnitureFactory()
create_room(victorian_factory)
Output
# Sitting on a modern chair.
# Dining on a modern table.
# Sitting on a Victorian chair.
# Dining on a Victorian table.