The Factory pattern provides a way to create objects without specifying the exact class. It centralizes object creation, which promotes flexibility and reduces direct dependencies in your code.
Sometimes your code needs to create different types of objects depending on conditions. Using hardcoded if
or switch
statements to decide which class to use can make your code harder to maintain. The Factory pattern simplifies this by putting the creation logic into one place. This allows you to add new object types without changing the code that uses them.
Use the Factory pattern when:
Avoid this pattern if:
The Factory pattern includes:
Think of ordering pizza at a restaurant. You don’t give instructions for how to make a Margherita—you just order it by name. The kitchen knows how to prepare it. In the same way, a factory method lets you request an object without knowing the details of how it’s created.
Here’s a basic Python example using static factory methods:
class Pizza:
def __init__(self, ingredients):
self.ingredients = ingredients
@staticmethod
def margherita():
return Pizza(['mozzarella', 'tomatoes'])
@staticmethod
def prosciutto():
return Pizza(['mozzarella', 'tomatoes', 'ham'])
# Usage:
p1 = Pizza.margherita()
print(p1.ingredients) # Output: ['mozzarella', 'tomatoes']
In this example:
Pizza
is the main product class.margherita()
and prosciutto()
are factory methods that return pre-configured pizza objects.Explore the full Python implementation here: Factory Pattern on GitHub