Skip to content

Lesson 4 of 28Principles

Creational Patterns

Use factories, builders and dependency injection to control how objects get made, and know why singletons cause pain.

28 min read0/8 questions

Every new StripeClient(...) or SmtpMailer(...) scattered through your code is a decision baked in place. Change the provider, add a test fake, or read a setting at startup, and you are hunting through dozens of files. Creational patterns put object creation in one deliberate spot, so the rest of the code just uses what it is given.

Factory: one place decides which class

A factory is a function (or method) that returns a new object, choosing which class to build from some input. Callers ask for "a notifier for this channel" and never import the concrete classes.

Python
class EmailNotifier: def __init__(self, sender: str): self.sender = sender def notify(self, user: str, text: str) -> str: return f"[email from {self.sender}] {user}: {text}" class SmsNotifier: def notify(self, user: str, text: str) -> str: return f"[sms] {user}: {text[:20]}" def create_notifier(channel: str): if channel == "email": return EmailNotifier(sender="noreply@shop.dev") if channel == "sms": return SmsNotifier() raise ValueError(f"unknown channel: {channel}") for channel in ["email", "sms"]: notifier = create_notifier(channel) print(notifier.notify("ada", "Your order has shipped and is on its way"))
Output
Press Run (⌘ Enter) to see what happens.

The if chain did not disappear. It moved to one place, and only that place changes when you add push notifications. Every caller is closed for modification, which is the Open/Closed principle from the SOLID lesson in action.

Two GoF relatives, briefly:

  • Factory Method: a base class calls self.create_exporter() and lets each subclass override that one method. Useful in frameworks; in app code, passing a factory function is usually simpler.
  • Abstract Factory: a factory that makes a whole family of matching objects. Think AwsCloud() returning an S3 storage and an SQS queue, while LocalCloud() returns a disk folder and an in-memory queue. You switch environments in one line and can never mix an S3 store with a local queue by accident.
Quick check
What is the main benefit of create_notifier(channel) over calling the classes directly?
Need a nudge? A hint rules out a wrong answer.

Factory Method and Abstract Factory, honestly

The Gang of Four book (1994) was written for C++ and Smalltalk, where a class was the only way to pass "something that makes objects" around. In Python and TypeScript, functions and classes are already values. That changes which factory shapes are worth writing.

Factory Method is about inheritance. A base class runs an algorithm and leaves one step, "make the object", to subclasses.

class ReportJob:
    def run(self, rows):
        exporter = self.create_exporter()  # the factory method
        return exporter.export(rows)
 
    def create_exporter(self):
        raise NotImplementedError
 
class CsvReportJob(ReportJob):
    def create_exporter(self):
        return CsvExporter()

You meet this mostly inside frameworks: Django's class-based views call get_queryset() and get_serializer_class(), which you override. In your own code it is usually simpler to pass the exporter, or a function that builds one, into the constructor. Composition gives you the same flexibility with no subclass per variant.

Abstract Factory is about consistency. Its value is not "making objects" but guaranteeing that the objects belong together. A test environment must never pair a real S3 bucket with an in-memory queue that drops messages. If you have that kind of family, one object with storage() and queue() methods is a good design. If you only have one product, an abstract factory is ceremony.

For a single product chosen by config, the honest Python answer is often a dict of constructors:

Python
from dataclasses import dataclass @dataclassclass S3Storage: bucket: str def save(self, key: str, data: bytes) -> str: return f"s3://{self.bucket}/{key}" @dataclassclass DiskStorage: root: str def save(self, key: str, data: bytes) -> str: return f"{self.root}/{key}" # The whole "factory": a dict from config value to constructor.STORAGE = { "s3": lambda cfg: S3Storage(bucket=cfg["bucket"]), "disk": lambda cfg: DiskStorage(root=cfg.get("root", "/tmp/uploads")),} def make_storage(cfg: dict): build = STORAGE.get(cfg.get("kind")) if build is None: raise ValueError(f"unknown storage kind {cfg.get('kind')!r}; expected one of {sorted(STORAGE)}") return build(cfg) print(make_storage({"kind": "s3", "bucket": "invoices"}).save("a.pdf", b""))print(make_storage({"kind": "disk"}).save("a.pdf", b""))try: make_storage({"kind": "gcs"})except ValueError as e: print(e)
Output
Press Run (⌘ Enter) to see what happens.

Two details matter more than the pattern name. The error message lists the valid options, so a typo in a config file is a ten-second fix instead of a debugging session. And the lookup is separate from the build, so a missing bucket key raises its own KeyError instead of being reported as "unknown storage kind". Catching KeyError around both is a common bug that hides the real problem.

In TypeScript the equivalent is a Record<Kind, (cfg) => Storage> typed so that every member of the Kind union must have an entry. Add "gcs" to the union and the compiler refuses to build until the factory knows about it.

Registries and plugin factories

A plain factory still has to import every concrete class. A registry flips that: each implementation registers itself under a name, and the factory just looks the name up. This is how the Open/Closed idea from the SOLID lesson scales to dozens of variants or to code you do not own.

Python
from typing import Callable, Protocol class Exporter(Protocol): def export(self, rows: list[dict]) -> str: ... _REGISTRY: dict[str, Callable[[], Exporter]] = {} def register(name: str): def wrap(cls): if name in _REGISTRY: raise RuntimeError(f"exporter {name!r} registered twice") _REGISTRY[name] = cls return cls return wrap def create_exporter(name: str) -> Exporter: if name not in _REGISTRY: raise ValueError(f"no exporter {name!r}; installed: {sorted(_REGISTRY)}") return _REGISTRY[name]() # These would normally live in separate modules: exporters/csv.py, exporters/shout.py@register("csv")class CsvExporter: def export(self, rows): return "\n".join(",".join(str(v) for v in r.values()) for r in rows) @register("upper")class ShoutingExporter: def export(self, rows): return str(rows).upper() rows = [{"id": 1, "plan": "pro"}]print(create_exporter("csv").export(rows))print(create_exporter("upper").export(rows))try: create_exporter("xml")except ValueError as e: print(e)
Output
Press Run (⌘ Enter) to see what happens.

The trap with decorator registries: registration happens at import time. If nothing imports exporters/xml.py, its @register("xml") line never runs, and the factory says "no exporter 'xml'" even though the file exists. Teams fix this by importing every plugin module in one place (an exporters/__init__.py that lists them), which is honest and easy to grep. The duplicate check matters too: without it, two modules registering "csv" silently overwrite each other, and which one wins depends on import order.

For plugins that live in other packages, Python has a standard mechanism: entry points. A plugin package declares what it offers in its pyproject.toml:

pyproject.toml (in the plugin package)
[project.entry-points."shop.exporters"]
xml = "shop_xml.exporter:XmlExporter"

Your app discovers every installed plugin without importing anything by name:

from importlib.metadata import entry_points
 
def load_exporters() -> dict:
    return {ep.name: ep.load() for ep in entry_points(group="shop.exporters")}

This is how pytest finds its plugins and how many CLI tools discover subcommands. pip install shop-xml is the whole installation step. The cost is that a broken plugin can now crash your startup, so load them defensively and log which ones failed.

Quick check
You add exporters/xml.py with @register("xml") on a class, but create_exporter("xml") says no such exporter. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.

Builder: step by step, readable at the call site

When an object has many optional parts, a constructor call like Request("POST", url, None, None, 30, True, headers) is unreadable and easy to get wrong. A Builder assembles it one named step at a time and checks everything in a final build(). A fluent builder returns itself from each step, so calls chain.

Python
class RequestBuilder: def __init__(self, method: str, url: str): self._req = {"method": method, "url": url, "headers": {}, "timeout": 10} def header(self, name: str, value: str) -> "RequestBuilder": self._req["headers"][name] = value return self def bearer(self, token: str) -> "RequestBuilder": return self.header("Authorization", f"Bearer {token}") def json(self, body: dict) -> "RequestBuilder": self._req["body"] = body return self.header("Content-Type", "application/json") def timeout(self, seconds: int) -> "RequestBuilder": self._req["timeout"] = seconds return self def build(self) -> dict: if self._req["method"] == "GET" and "body" in self._req: raise ValueError("GET requests cannot have a body") return self._req req = ( RequestBuilder("POST", "https://api.shop.dev/refunds") .bearer("tok_123") .json({"charge": "ch_9", "amount": 500}) .timeout(5) .build())print(req["headers"])print(req["timeout"])
Output
Press Run (⌘ Enter) to see what happens.

You use builders constantly without writing them: SQLAlchemy's select(User).where(User.active).order_by(User.created_at), Prisma queries, and test data helpers like a_user().with_plan("pro").build().

Predict the outputPython

What does this print?

class B:
  def __init__(self):
      self.parts = []
  def add(self, p):
      self.parts.append(p)
      return self
  def build(self):
      return "-".join(self.parts)

b = B().add("a").add("b")
b.add("c")
print(b.build())
Need a nudge? Hints walk you through it.

Prototype: clone a configured object

Prototype means making a new object by copying an existing, already configured one instead of building it from scratch. In C++ that needed a clone() method on every class. In Python and TypeScript the language gives you the copy, so the pattern shrinks to one decision that actually matters: shallow or deep.

You use it for plan templates ("start from the Pro plan, then change the seat count"), test fixtures, and default settings that each request may tweak. The bug is always the same: you thought you made a copy, but a nested object is still shared.

Predict the outputPython

What does this print?

import copy

template = {"plan": "pro", "limits": {"seats": 5}, "tags": ["beta"]}

shallow = copy.copy(template)
deep = copy.deepcopy(template)

shallow["limits"]["seats"] = 50
deep["tags"].append("vip")

print(template["limits"]["seats"], template["tags"])
Need a nudge? Hints walk you through it.

TypeScript and modern JavaScript have structuredClone, available in every current browser and in Node 17 and later. It handles nested objects, Date, Map, Set and even cycles. It does not keep class identity: a class instance comes back as a plain object without its methods, and a function anywhere in the value throws a DataCloneError.

TypeScript
class Money { constructor(public cents: number) {} format() { return `$${(this.cents / 100).toFixed(2)}`; }} const template = { plan: "pro", limits: { seats: 5 }, createdAt: new Date(0), price: new Money(900) }; const spread = { ...template }; // shallow: nested objects sharedconst cloned = structuredClone(template); // deep: Dates, Maps, Sets survive spread.limits.seats = 50;cloned.limits.seats = 99; console.log(template.limits.seats); // 50, the spread leaked throughconsole.log(cloned.createdAt instanceof Date); // trueconsole.log(cloned.price instanceof Money); // false: class prototypes are droppedconsole.log("format" in cloned.price); // false: no methods either
Output
Press Run (⌘ Enter) to see what happens.

Notice that TypeScript still types cloned.price as Money, so the compiler will happily let you call cloned.price.format() and it fails at run time. When you clone domain objects with behaviour, write an explicit clone() or with...() method that calls the constructor. That is the original pattern, and it is still the right tool when a plain deep copy is not enough. Better still, make the template immutable (@dataclass(frozen=True) with dataclasses.replace, or readonly types with spreads), and you never need a defensive copy at all.

Singleton: the pattern to be wary of

A Singleton guarantees a class has exactly one instance and gives global access to it. It sounds handy for a config object or a database pool.

Python
class Settings: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.currency = "USD" return cls._instance a = Settings()b = Settings()a.currency = "EUR"print(a is b, b.currency) # a test that set EUR now leaks into every other test
Output
Press Run (⌘ Enter) to see what happens.

The problems are all versions of "hidden global state":

  • Hidden dependencies. A function that calls Settings() inside does not say so in its signature.
  • Tests leak. One test changes the singleton and the next test sees it.
  • Hard to swap. You cannot give one request a different instance.

The pragmatic alternatives: in Python, a module-level instance (settings = Settings() in config.py) is already a singleton, because a module is imported once. In TypeScript, an exported const from an ES module behaves the same. And for anything you want to swap in tests, use dependency injection.

Quick check
Your tests pass alone but fail when run together. The code uses PaymentClient.instance() everywhere. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.

Object pools: reuse only what is expensive

An object pool keeps a set of ready-made objects and lends them out instead of creating new ones. In the 1990s people pooled ordinary objects to dodge slow allocation. Today that is almost always a mistake: allocation in Python, the JVM, .NET and V8 is cheap, and a pool of plain objects adds shared mutable state and reset bugs for no gain.

Pools still matter for one kind of object: things that are expensive to open and limited on the other side. A database connection costs a TCP handshake, TLS, and authentication, often tens of milliseconds, and Postgres allows only a fixed number of connections in total. Thread pools, HTTP keep-alive connection pools and GPU sessions fit the same shape. You use pools every day through libraries: SQLAlchemy's engine, psycopg_pool, pg.Pool in Node, and the global dispatcher behind Node's fetch all keep connections open between requests.

Python
from contextlib import contextmanager class PoolExhausted(Exception): pass class Connection: opened = 0 def __init__(self): Connection.opened += 1 # imagine TCP + TLS + auth: tens of ms self.id = Connection.opened def query(self, sql: str) -> str: return f"conn{self.id}: {sql}" class Pool: def __init__(self, size: int): self.size = size self.idle: list[Connection] = [] self.in_use = 0 @contextmanager def connection(self): if self.idle: conn = self.idle.pop() elif self.in_use < self.size: conn = Connection() else: raise PoolExhausted(f"all {self.size} connections in use") self.in_use += 1 try: yield conn finally: # returned even if the query raises self.in_use -= 1 self.idle.append(conn) pool = Pool(size=2)for i in range(5): # five requests, one after another with pool.connection() as conn: print(conn.query(f"select {i}"))print("connections opened:", Connection.opened) # Two requests hold their connections while a third arriveswith pool.connection(), pool.connection(): try: with pool.connection(): pass except PoolExhausted as e: print("third request:", e)
Output
Press Run (⌘ Enter) to see what happens.

Five requests, one connection opened. That is the whole point. A real pool makes the third request wait for a while before giving up, rather than failing at once, but the failure modes are the same ones you will debug in production:

  • Leaks. Code that borrows a connection and forgets to return it on an error path. After enough errors the pool is empty and every request times out. The with block (or try/finally) is not optional.
  • Exhaustion under load. A slow query holds its connection longer, so more requests wait, so latency climbs everywhere. Pool size is a capacity decision, not a default to ignore.
  • Too many pools. Every process gets its own pool. Twenty containers with a pool of 10 each is 200 database connections, which can exceed the server's limit. This is why tools like PgBouncer exist.
  • Stale connections. The database or a load balancer drops idle connections. Pools solve this with a liveness check before lending (SQLAlchemy calls it pool_pre_ping) or a maximum connection age.
  • Fork. A pool created before a process forks shares sockets between parent and child. Create pools after the fork, in each worker.
Quick check
Which of these is a good candidate for an object pool in a modern Python or TypeScript service?
Need a nudge? A hint rules out a wrong answer.

Dependency injection: the modern answer

Dependency injection (DI) means an object receives what it needs instead of creating it. All the real objects are built in one place at startup, called the composition root (your main.py, or a Next.js server module). Everything else just accepts parameters.

Wiring in the composition root
maincomposition root, builds everything oncesettingsread from envdb_pooluses settingsStripeGatewayuses settingsOrderRepositoryuses db_poolOrderRepository (injected)StripeGateway (injected)CheckoutServicegets repo + gatewayroot

One function builds the object graph. It is the only place that knows the concrete classes.

1/4
Python
class FakeGateway: def charge(self, cents: int) -> str: return f"fake-charge-{cents}" class StripeGateway: def __init__(self, api_key: str): self.api_key = api_key def charge(self, cents: int) -> str: return f"stripe-charge-{cents}" class CheckoutService: def __init__(self, gateway): self.gateway = gateway def pay(self, cents: int) -> str: return self.gateway.charge(cents) def build_app(env: str) -> CheckoutService: # composition root gateway = FakeGateway() if env == "test" else StripeGateway(api_key="sk_live_x") return CheckoutService(gateway) print(build_app("prod").pay(1200))print(build_app("test").pay(1200))
Output
Press Run (⌘ Enter) to see what happens.

You do not need a DI framework for this. Constructor parameters are enough. FastAPI's Depends and Angular's injector automate the wiring, but the idea is the same.

DI containers vs manual wiring

Manual wiring is a build_app() function that calls constructors in the right order, like the composition root above. A DI container is a library that does that wiring for you: you register "when someone needs a PaymentGateway, give them a StripeGateway", and the container builds the graph by reading constructor signatures or decorators.

Containers differ, but three ideas are common to all of them, and they come up in interviews about NestJS, Spring and ASP.NET Core:

  • Registration: mapping an abstraction to a concrete class or a factory function.
  • Resolution: asking for the top object, and the container builds everything it needs first.
  • Lifetimes: whether an object is created once for the whole app (singleton), once per request (scoped), or every time it is asked for (transient).

Lifetimes are where real bugs live. The classic is the captive dependency: a singleton that takes a scoped object in its constructor. The singleton is built once, so it captures the first request's database session or current user and keeps it forever. Later requests read another user's data through a stale session. Some containers detect this at startup. Manual wiring makes it visible, because you can see that build_app() runs once while the session factory runs per request.

A captive dependency leaking one user's session
Request AContainerReportService (singleton)Request Bresolve ReportServicenew ReportService(session_A)Ada's reportsresolve ReportServiceAda's reports (stale session_A)

The first request needs the service. The container builds it once, because it is registered as a singleton.

1/5

FastAPI shows the middle ground well. Depends is a small container: it resolves function parameters per request, caches each dependency within one request, and runs cleanup code after a yield.

app/deps.py
from typing import Annotated
from fastapi import Depends, FastAPI
 
def get_session():
    session = SessionLocal()   # scoped: one per request
    try:
        yield session
    finally:
        session.close()
 
def get_orders(session: Annotated[Session, Depends(get_session)]) -> OrderRepository:
    return OrderRepository(session)
 
app = FastAPI()
 
@app.post("/orders")
def create_order(body: NewOrder, orders: Annotated[OrderRepository, Depends(get_orders)]):
    return orders.add(body)

In tests you swap a dependency without patching anything: app.dependency_overrides[get_orders] = lambda: FakeOrders(). That one line is the payoff of injection.

In TypeScript, NestJS and Angular have containers built in, and if you use those frameworks you use their injector. For other projects, tsyringe and InversifyJS exist, but both rely on the legacy experimentalDecorators mode and reflect-metadata to read constructor types at run time, because TypeScript types are erased when compiled. Check each library's docs for current requirements before adopting one.

Manual wiringDI container
SetupA function you can read top to bottomRegistrations, decorators, config
ErrorsFail at startup, on the line that is wrongOften at resolution time, with a long stack trace
LifetimesYou write them (build once vs per request)Declared, and enforced by some containers
ScaleFine up to a few dozen servicesPays off with large graphs and many scopes
Best fitMost Python and Node servicesFramework apps (NestJS, Angular, Spring, .NET)

A sensible rule: start with constructor parameters and one composition root. Adopt a container when your framework already ships one, or when the hand-written wiring has become the part of the code that changes most often. A container never fixes a design where objects reach for globals. It only automates passing things in, so the design has to accept things being passed in first.

Put it in order5 steps

Your composition root builds a checkout service. Put the construction steps in the order they must run.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/4 matched

Match each problem to the pattern that fits.

Choose an item, then its match on the other side.
ChallengeEasy

Exporter factory

Build three exporters and a factory that picks one.

  • CsvExporter().export(rows): a header line of the first row's keys, then one line per row, joined with \n. Values joined with ,.
  • TsvExporter().export(rows): the same, separated by tabs (\t).
  • JsonExporter().export(rows): compact JSON with no spaces (Python: json.dumps(rows, separators=(",", ":")), TypeScript: JSON.stringify(rows)).
  • An empty list exports as "" for CSV and TSV, and "[]" for JSON.

create_exporter(fmt) (TypeScript: createExporter(fmt)) returns a new instance for "csv", "tsv" or "json", ignoring case. Any other format raises ValueError (TypeScript: throws an Error) whose message includes the format name.

create_exporter("CSV").export([{"id": 1, "plan": "pro"}])  ->  "id,plan\n1,pro"
create_exporter("xml")                                    ->  ValueError: unsupported format: xml
import json class CsvExporter: def export(self, rows: list[dict]) -> str: pass class TsvExporter: def export(self, rows: list[dict]) -> str: pass class JsonExporter: def export(self, rows: list[dict]) -> str: pass def create_exporter(fmt: str): # Return a new exporter for "csv", "tsv" or "json" (any case). pass
ChallengeEasy

Fluent email builder

Write a fluent EmailBuilder. Each step returns the builder itself so calls chain:

EmailBuilder().to("ada@example.com").to("sam@example.com").subject("Invoice").body("Attached.").build()
->  {"to": ["ada@example.com", "sam@example.com"], "subject": "Invoice", "body": "Attached."}
  • to(address) adds a recipient (it can be called several times)
  • subject(text) and body(text) set those fields; body defaults to ""
  • build() returns a dict (TypeScript: a plain object { to, subject, body })
  • build() raises ValueError (TypeScript: throws an Error) if there is no recipient or no subject
  • the built email must be a snapshot: adding another recipient to the builder afterwards must not change an email you already built
class EmailBuilder: def __init__(self): pass def to(self, address: str) -> "EmailBuilder": pass def subject(self, text: str) -> "EmailBuilder": pass def body(self, text: str) -> "EmailBuilder": pass def build(self) -> dict: pass
Key terms
factory
A function or method that creates and returns an object, deciding which concrete class to use.
abstract factory
A factory that creates a family of related objects that are meant to be used together.
builder
An object that assembles a complex value step by step and validates it in a final build().
singleton
A class restricted to one global instance. Usually replaced by one instance created at startup and injected.
dependency injection
Passing an object the things it needs instead of letting it construct them.
composition root
The single place at startup where the real objects are built and wired together.
registry
A lookup table that implementations add themselves to by name, so a factory can create them without importing each one.
entry point
A named hook declared in a Python package's metadata that lets an app discover installed plugins.
prototype
Creating a new object by copying an existing configured one. Watch whether the copy is shallow or deep.
object pool
A set of ready objects lent out and returned, worth it only for costly, limited resources such as database connections.
DI container
A library that builds the object graph from registrations and manages each object's lifetime.
captive dependency
A long-lived object that holds a shorter-lived one, such as a singleton keeping the first request's database session.