Creational Factory Builder

Factory Method, Abstract Factory, Builder (GoF Creational)

"Creational patterns abstract the instantiation process." — GoF, Design Patterns


What these three patterns have in common

They hide the complexity of creating an object from its user. All three do it differently:


1. Factory Method

Canonical form (GoF)

from abc import ABC, abstractmethod

class Document(ABC):
    @abstractmethod
    def render(self) -> str: ...

class PdfDocument(Document):
    def render(self): return "PDF rendered"

class HtmlDocument(Document):
    def render(self): return "HTML rendered"


class DocumentCreator(ABC):
    @abstractmethod
    def create_document(self) -> Document: ...

    def render_and_save(self):
        doc = self.create_document()                # ← Factory Method
        return doc.render()


class PdfCreator(DocumentCreator):
    def create_document(self): return PdfDocument()


class HtmlCreator(DocumentCreator):
    def create_document(self): return HtmlDocument()

Structure: the Creator hierarchy is parallel to the Product hierarchy. Each Creator knows which Product to create.

In Python this is overkill. The classic form needs two parallel hierarchies (Creator + Product). Java needed the boilerplate because it had no first-class functions. Python is simpler.

The Pythonic form: @classmethod

@dataclass(frozen=True)
class Document:
    content: str
    format: str

    @classmethod
    def from_pdf(cls, pdf_bytes: bytes) -> "Document":
        content = parse_pdf(pdf_bytes)
        return cls(content=content, format="pdf")

    @classmethod
    def from_html(cls, html: str) -> "Document":
        return cls(content=html, format="html")

    @classmethod
    def from_db_row(cls, row: dict) -> "Document":
        return cls(content=row["content"], format=row["format"])


# Usage:
doc = Document.from_pdf(file_bytes)
doc = Document.from_html("<h1>Hi</h1>")
doc = Document.from_db_row(row)

This is the Pythonic replacement for Factory Method. A technical note: the classic GoF Factory Method needs parallel hierarchies (Creator and Product) with polymorphic selection in subclasses. A named constructor (@classmethod from_X) is a separate pattern (the term is Joshua Bloch's, Effective Java) that fills the same role in 95% of cases in Python.

Examples from the standard library are named constructors, not GoF Factory Method in the strict sense:

When to apply

  1. Several different paths to create the same type (from a file, from a DB, from an API).
  2. Complex initialisation logic that does not fit a simple __init__.
  3. A semantically named alternative to the constructor (User.guest(), Money.zero()).

When NOT to apply


2. Abstract Factory

Canonical form (GoF)

Creating a family of related objects:

class Button(Protocol):
    def render(self): ...

class TextField(Protocol):
    def render(self): ...


# WindowsFamily:
class WindowsButton:
    def render(self): return "[Win Button]"

class WindowsTextField:
    def render(self): return "[Win TextField]"


# MacFamily:
class MacButton:
    def render(self): return "[Mac Button]"

class MacTextField:
    def render(self): return "[Mac TextField]"


# Abstract Factory:
class UIFactory(Protocol):
    def create_button(self) -> Button: ...
    def create_text_field(self) -> TextField: ...


class WindowsUIFactory:
    def create_button(self): return WindowsButton()
    def create_text_field(self): return WindowsTextField()


class MacUIFactory:
    def create_button(self): return MacButton()
    def create_text_field(self): return MacTextField()


# Usage:
def build_form(factory: UIFactory):
    btn = factory.create_button()                  # ← guaranteed from the same family
    field = factory.create_text_field()             # ← same family
    return [btn, field]


# Composition Root:
factory = WindowsUIFactory() if os.name == "nt" else MacUIFactory()
form = build_form(factory)

Key idea: the UI cannot accidentally mix WindowsButton with MacTextField. The factory guarantees family consistency.

When to apply

When NOT to apply

In Python, Abstract Factory is rare (~5% of real projects). It mostly appears in frameworks (SQLAlchemy dialects, Django backends).


3. Builder

Canonical form (GoF)

class EmailBuilder:
    def __init__(self):
        self._to: list[str] = []
        self._cc: list[str] = []
        self._subject: str = ""
        self._body: str = ""
        self._attachments: list[bytes] = []
        self._priority: str = "normal"

    def to(self, addr: str) -> "EmailBuilder":
        self._to.append(addr)
        return self                                  # ← fluent interface

    def cc(self, addr: str) -> "EmailBuilder":
        self._cc.append(addr)
        return self

    def subject(self, s: str) -> "EmailBuilder":
        self._subject = s
        return self

    def body(self, b: str) -> "EmailBuilder":
        self._body = b
        return self

    def attachment(self, data: bytes) -> "EmailBuilder":
        self._attachments.append(data)
        return self

    def priority(self, p: str) -> "EmailBuilder":
        if p not in ("low", "normal", "high"):
            raise ValueError(f"invalid priority: {p}")
        self._priority = p
        return self

    def build(self) -> "Email":
        if not self._to:
            raise ValueError("at least one recipient required")
        if not self._subject:
            raise ValueError("subject required")
        return Email(
            to=tuple(self._to),
            cc=tuple(self._cc),
            subject=self._subject,
            body=self._body,
            attachments=tuple(self._attachments),
            priority=self._priority,
        )


@dataclass(frozen=True)
class Email:
    to: tuple[str, ...]
    cc: tuple[str, ...]
    subject: str
    body: str
    attachments: tuple[bytes, ...]
    priority: str


# Usage:
email = (EmailBuilder()
    .to("[email protected]")
    .to("[email protected]")
    .cc("[email protected]")
    .subject("Quarterly Report")
    .body("See attached")
    .attachment(pdf_bytes)
    .priority("high")
    .build())

Key signs of Builder:

When to apply

  1. An object with 5+ optional parameters.
  2. Step-by-step construction with validation at each step.
  3. Different combinations — Builder lets you create many variants through one piece of infrastructure.
  4. You want a readable description of the object in code — a fluent interface reads better than a big __init__ with 10 parameters.

When NOT to apply, and why Python often does not need Builder

@dataclass(kw_only=True) often replaces Builder:

@dataclass(frozen=True, kw_only=True)
class Email:
    to: tuple[str, ...]
    subject: str
    cc: tuple[str, ...] = ()
    body: str = ""
    attachments: tuple[bytes, ...] = ()
    priority: str = "normal"

    def __post_init__(self):
        if not self.to:
            raise ValueError("at least one recipient required")
        if self.priority not in ("low", "normal", "high"):
            raise ValueError(f"invalid priority: {self.priority}")


# Usage:
email = Email(
    to=("[email protected]", "[email protected]"),
    cc=("[email protected]",),
    subject="Quarterly Report",
    body="See attached",
    attachments=(pdf_bytes,),
    priority="high",
)

This is almost the same as Builder, without 30 lines of boilerplate:

When Builder is still justified:

  1. Accumulating fields with logic — several .to(addr) calls add to a list.
  2. Complex cross-step validation — "you cannot call .priority(high) without .subject()".
  3. API for external clients where fluent reads better.
  4. Step-by-step IDE hints — each .with_X() suggests the next step.

Rule: start with @dataclass(kw_only=True). When it gets tight, move to Builder.


A Pythonic combined example: pathlib.Path

path = Path.home() / "documents" / "report.pdf"

Path.home() is a Factory Method (@classmethod with no arguments). The / operator that appends segments is a Builder-style fluent interface.

pathlib combines both patterns in a natural API.


Anti-patterns

1. Factory Method for one variant

class User:
    @classmethod
    def create(cls, name, email):
        return cls(name=name, email=email)         # ← same as __init__!

If from_X adds nothing to __init__, do not extract it.

2. Builder for a simple object

PointBuilder().x(1).y(2).build()                  # instead of Point(1, 2)

If you have 2-3 parameters, Builder is over-engineering. Point(1, 2) is enough.

3. Abstract Factory without families

class WidgetFactory(Protocol):
    def create_button(self) -> Button: ...
    # only one implementation, only one type

A "family" of one object is not Abstract Factory, it is plain Factory Method.

4. Builder that returns a mutable object

email = EmailBuilder().to("...").build()
email.priority = "high"                           # ← bypassing the builder!

Builder + mutable result is pointless. The result should be frozen.

5. Mixed Factory Method + Builder without need

class EmailBuilder:
    @classmethod
    def simple(cls, to, subject, body):
        return cls().to(to).subject(subject).body(body).build()

Pick one: Factory Method or Builder. Both together is noise. If simple is popular, let Email have an Email.simple(...) classmethod, no builder.


Rules of thumb

  1. @classmethod from_X is the Python Factory Method standard. Not the Java-style parallel hierarchies.
  2. @dataclass(kw_only=True) is the Pythonic Builder. Move to a real Builder only when truly needed.
  3. Abstract Factory is rare. Seen in frameworks, not in everyday apps.
  4. Builder result is always frozen. Otherwise the pattern has no point.
  5. Do not multiply from_X. One or two is normal. Five is suspicious.
  6. Factory Method names are semantic, not mechanical. from_json, not create_from_json. User.new(), Money.zero(), Order.empty().
  7. Between Factory Method and __init__, __init__ is the default. Factory Method when you need a second named path.

One-line summary

Factory Method = @classmethod with a name. Builder = fluent for many-parameter objects. Abstract Factory = the rare case of a real family. In Python the language often covers all three, so start simple and add complexity only as needed.