Understanding Factory Method, Abstract Factory, and Builder Design Patterns with Python Examples
This article explains the concepts, differences, and practical Python implementations of the Factory Method, Abstract Factory, and Builder design patterns, highlighting when to use each, their advantages, and providing clear code examples.
Both the Factory Method and Builder patterns belong to the creational design patterns family. In the Factory pattern, the client requests an object without knowing its concrete class, simplifying the object creation process.
The Factory pattern typically appears in two forms: the simple Factory Method, which is a single function returning different objects based on input parameters, and the Abstract Factory, a collection of factory methods that create a family of related objects.
When object‑creation code is scattered across many places, making it hard to track, the Factory Method centralizes creation, decouples construction from use, and can improve performance and memory usage by creating objects only when necessary.
# Factory Method Example: HTML Button Factory
class Button(object):
html = "<button></button>"
def get_html(self):
return self.html
class Image(Button):
html = "<img></img>"
class Input(Button):
html = "<input></input>"
def create_button(name):
c_name = name.capitalize()
if c_name in ['Button', 'Image', 'Input']:
return globals()[c_name]()
print(create_button('image').get_html()) # <img></img>Multiple factory methods can be encapsulated within a class for better organization:
# Factory Method Example 2: Encapsulating in HTMLFactory
class HTMLFactory:
button_types = ['Button', 'Image', 'Input']
def create_button(self, name):
c_name = name.capitalize()
if c_name in self.button_types:
return globals()[c_name]()
print(HTMLFactory().create_button('button').get_html()) # <button></button>The Abstract Factory pattern generalizes the Factory Method by providing a set of related factory methods. For example, a toy factory can produce different families of toys:
# Abstract Factory Example: Toy Factory
from abc import ABC, abstractmethod
class AbstractToy(ABC):
@abstractmethod
def name(self) -> str:
pass
@abstractmethod
def price(self) -> int:
pass
class AbstractFactory(ABC):
@abstractmethod
def create_toy(self, name) -> AbstractToy:
pass
class CarToyFactory(AbstractFactory):
types = ['BMW', 'Porsche', 'Buick']
def create_toy(self, name):
return "Car Toy:" + name
class StuffedToyFactory(AbstractFactory):
types = ['Bear', 'Cat', 'Dog']
def create_toy(self, name):
return "Stuffed Toy:" + name
factory = CarToyFactory()
print(factory.create_toy('BMW')) # Car Toy:BMWThe Builder pattern is used when creating a complex object that requires multiple steps or a specific construction order. A fluent builder example for a Pizza object demonstrates how to chain configuration methods before building the final product:
# Fluent Builder Example
class Pizza:
def __init__(self, builder):
self.garlic = builder.garlic
self.extra_cheese = builder.extra_cheese
def __str__(self):
garlic = 'yes' if self.garlic else 'no'
cheese = 'yes' if self.extra_cheese else 'no'
return f"Garlic: {garlic}
Extra cheese: {cheese}"
class PizzaBuilder:
def __init__(self):
self.garlic = False
self.extra_cheese = False
def add_garlic(self):
self.garlic = True
return self
def add_extra_cheese(self):
self.extra_cheese = True
return self
def build(self):
return Pizza(self)
if __name__ == '__main__':
pizza = PizzaBuilder().add_garlic().add_extra_cheese().build()
print(pizza)In summary, the Factory pattern comes in two forms—Factory Method and Abstract Factory—with a preference for the simpler Factory Method when appropriate. Its advantages include decoupling object creation from usage, easier modifications, and potential performance gains. The Builder pattern complements these by handling the construction of complex objects through a step‑by‑step process.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
