Lesson 4 of 28Principles
Creational Patterns
Use factories, builders and dependency injection to control how objects get made, and know why singletons cause pain.
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.
Press Run (⌘ Enter) to see what happens.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, whileLocalCloud()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.
create_notifier(channel) over calling the classes directly?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:
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.
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:
[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.
exporters/xml.py with @register("xml") on a class, but create_exporter("xml") says no such exporter. What is the most likely cause?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.
Press Run (⌘ Enter) to see what happens.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().
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())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.
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"])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.
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.
Press Run (⌘ Enter) to see what happens.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.
PaymentClient.instance() everywhere. What is the most likely cause?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.
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
withblock (ortry/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.
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.
One function builds the object graph. It is the only place that knows the concrete classes.
Press Run (⌘ Enter) to see what happens.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.
The first request needs the service. The container builds it once, because it is registered as a singleton.
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.
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 wiring | DI container | |
|---|---|---|
| Setup | A function you can read top to bottom | Registrations, decorators, config |
| Errors | Fail at startup, on the line that is wrong | Often at resolution time, with a long stack trace |
| Lifetimes | You write them (build once vs per request) | Declared, and enforced by some containers |
| Scale | Fine up to a few dozen services | Pays off with large graphs and many scopes |
| Best fit | Most Python and Node services | Framework 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.
Your composition root builds a checkout service. Put the construction steps in the order they must run.
- Tap the steps below in the right order.
Match each problem to the pattern that fits.
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: xmlFluent 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)andbody(text)set those fields;bodydefaults to""build()returns a dict (TypeScript: a plain object{ to, subject, body })build()raisesValueError(TypeScript: throws anError) 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
- 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.