Fundamentals 8 min read

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.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding Factory Method, Abstract Factory, and Builder Design Patterns with Python 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.

<code># 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> </code>

Multiple factory methods can be encapsulated within a class for better organization:

<code># 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> </code>

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:

<code># 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:BMW </code>

The 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:

<code># 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}\nExtra 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) </code>

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.

design patternspythonabstract factoryFactory MethodBuilder Pattern
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.