Design Patterns I — Creational
What you’ll learn. What design patterns are and are not; the creational patterns that control how objects get made (Factory Method, Abstract Factory, Builder, Prototype, Singleton); why Singleton is considered harmful in most code; and how dependency injection and language features (default arguments, dataclasses, first-class functions) have replaced much of this catalog. Code is Python or TypeScript, labelled.
What patterns are
Section titled “What patterns are”The 1994 book Design Patterns (Gamma, Helm, Johnson, Vlissides, the “Gang of Four” or GoF) catalogued 23 recurring solutions to object-oriented design problems. A pattern is a named problem-context-solution triple, valuable chiefly as shared vocabulary (“let’s put a Facade there”) and as a memory of trade-offs. It is not a library you import.
Two honest caveats. First, many GoF patterns compensate for limitations of 1990s C++/Java (no first-class functions, no generics, no closures). In Python or TypeScript, Strategy is often a function and Iterator is a built-in protocol. Peter Norvig noted in 1996 that 16 of 23 patterns are invisible or simpler in Lisp/Dylan. Second, patterns applied without the forces that motivate them just add indirection (see Core Principles: YAGNI).
Creational patterns abstract the instantiation process. The core problem: new ConcreteClass(...) hard-codes a dependency on a concrete type at the call site.
Factory Method
Section titled “Factory Method”Problem. Code needs an object but should not know its exact class; the choice depends on context or should be extensible.
Idea. Define a method whose job is to create objects; subclasses or configuration decide the concrete type.
# Python: classic Factory Method via subclassingfrom abc import ABC, abstractmethod
class Exporter(ABC): @abstractmethod def make_serializer(self) -> "Serializer": ... def export(self, data) -> str: # uses the product via its interface return self.make_serializer().dumps(data)
class JsonExporter(Exporter): def make_serializer(self): return JsonSerializer()
class CsvExporter(Exporter): def make_serializer(self): return CsvSerializer()In practice you rarely need the class hierarchy. A simple factory (a function or static method, not strictly a GoF pattern) plus a registry covers most cases:
// TypeScript: simple factory with a registry (open for extension)interface Notifier { send(to: string, msg: string): Promise<void> }
const registry = new Map<string, () => Notifier>();export const registerNotifier = (kind: string, make: () => Notifier) => registry.set(kind, make);
export function createNotifier(kind: string): Notifier { const make = registry.get(kind); if (!make) throw new Error(`Unknown notifier: ${kind}`); return make();}
registerNotifier("email", () => new EmailNotifier());registerNotifier("sms", () => new SmsNotifier());Use when: construction logic is non-trivial, the concrete type depends on runtime input (config, file extension, message type), or you want one place to change. Python’s classmethod alternative constructors (datetime.fromtimestamp, dict.fromkeys) are idiomatic factory methods.
Abstract Factory
Section titled “Abstract Factory”Problem. You must create families of related objects that are meant to be used together, and you need to swap whole families.
Idea. An interface with several creation methods, one per product in the family; each concrete factory produces a consistent family.
// TypeScript: UI toolkit familiesinterface Button { render(): string }interface Checkbox { render(): string }
interface UiFactory { button(): Button; checkbox(): Checkbox;}
class DarkFactory implements UiFactory { button() { return { render: () => "[dark button]" }; } checkbox() { return { render: () => "[dark checkbox]" }; }}class LightFactory implements UiFactory { button() { return { render: () => "[light button]" }; } checkbox() { return { render: () => "[light checkbox]" }; }}
function renderForm(f: UiFactory) { return [f.button().render(), f.checkbox().render()].join(" ");}Client --> UiFactory (interface) ^ ^ DarkFactory LightFactory creates Dark* creates Light*Real-world instances: database driver layers (connection + statement + cursor from the same vendor), cross-platform GUI toolkits, test doubles bundles (“all fakes” vs “all real”). The downside: adding a new product type to the family forces changing every factory. Modern code often replaces Abstract Factory with a plain dataclass of callables or with DI configuration.
Builder
Section titled “Builder”Problem. An object has many optional parts or a multi-step construction; constructors with a dozen parameters (the “telescoping constructor”) are unreadable and error-prone.
Idea. Separate construction from representation: assemble step by step, then produce the final object.
// TypeScript: fluent builder with validation at build()class HttpRequest { constructor( readonly method: string, readonly url: string, readonly headers: Readonly<Record<string, string>>, readonly body?: string, readonly timeoutMs: number = 30_000, ) {}}
class HttpRequestBuilder { private method = "GET"; private headers: Record<string, string> = {}; private body?: string; private timeoutMs = 30_000; constructor(private url: string) {}
withMethod(m: string) { this.method = m; return this; } header(k: string, v: string) { this.headers[k] = v; return this; } json(payload: unknown) { this.body = JSON.stringify(payload); this.headers["content-type"] = "application/json"; return this; } timeout(ms: number) { this.timeoutMs = ms; return this; } build(): HttpRequest { if (this.method === "GET" && this.body) throw new Error("GET cannot have a body"); return new HttpRequest(this.method, this.url, { ...this.headers }, this.body, this.timeoutMs); }}
const req = new HttpRequestBuilder("https://api.example.com/users") .withMethod("POST").json({ name: "Ada" }).timeout(5000).build();Python often does not need a Builder at all: keyword arguments with defaults and @dataclass(frozen=True) give named, optional, immutable construction.
# Python: keyword-only args + frozen dataclass replace most Buildersfrom dataclasses import dataclass, field, replace
@dataclass(frozen=True)class HttpRequest: url: str method: str = "GET" headers: dict[str, str] = field(default_factory=dict) body: str | None = None timeout_s: float = 30.0
def __post_init__(self): if self.method == "GET" and self.body: raise ValueError("GET cannot have a body")
r = HttpRequest("https://api.example.com/users", method="POST", body="{}")r2 = replace(r, timeout_s=5) # copy-with-changesBuilder remains valuable when construction has ordering, needs validation across fields at the end, produces different products from the same steps (the GoF “Director” idea), or builds complex trees (SQL query builders, test-data builders, HTML/DOM construction). Test-data builders (aUser().withAdminRole().build()) are one of the most productive uses; see Testing & Code Quality.
Prototype
Section titled “Prototype”Problem. Creating an object from scratch is expensive or complex, but you can copy an existing, configured one.
Idea. Clone a prototypical instance rather than instantiating from a class.
# Python: Prototype via copy, with a registry of preconfigured prototypesimport copy
class Enemy: def __init__(self, hp: int, loot: list[str]): self.hp, self.loot = hp, loot def clone(self) -> "Enemy": return copy.deepcopy(self) # deep copy: loot list is not shared
prototypes = {"goblin": Enemy(30, ["coin"]), "ogre": Enemy(200, ["club", "coin"])}g1 = prototypes["goblin"].clone()g1.loot.append("gem") # prototype's loot unaffectedThe central pitfall is shallow vs deep copy: a shallow copy shares nested mutable objects, producing aliasing bugs. Prototype is built into JavaScript’s object model (prototype chains) and in structuredClone (TypeScript/JS) for deep copies. Immutable data makes Prototype mostly unnecessary: “copy with modification” (replace, spread syntax {...obj, x: 1}) is the functional equivalent. Use cases: game entity spawning, document templates, expensive-to-compute configured objects.
Singleton and why it is a problem
Section titled “Singleton and why it is a problem”Intent. Ensure a class has exactly one instance and provide a global access point.
# Python: the naive singletonclass Config: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.values = {} return cls._instanceIn Python the simplest “singleton” is a module-level object (modules are imported once). In TypeScript, export const config = new Config() does the same.
The pattern bundles two separate ideas: one instance (a lifecycle decision) and global access (a visibility decision). The second is the poison.
Problems:
- Hidden dependencies. A function that calls
Config.instance()has a dependency not visible in its signature. You must read the body to learn what it needs. - Global mutable state. Any code anywhere can change it, so behavior depends on invisible history. This is common coupling, one of the worst kinds (Core Principles).
- Testing pain. Tests share state through the singleton and become order-dependent; you cannot substitute a fake without hacks (monkeypatching, reset methods).
- Concurrency hazards. Lazy initialization is racy without locking (double-checked locking famously required
volatilein Java); shared mutable state needs synchronization (Concurrency). - Violates SRP. The class manages both its job and its own lifecycle.
- “Single” is rarely a true requirement. The need for a second instance (a test, a multi-tenant deployment, a second DB) appears later and is painful to retrofit.
What to do instead. Create one instance at the application’s entry point (the composition root) and pass it in to whoever needs it. You keep the single-instance lifecycle without global access. This is dependency injection.
Legitimate singletons exist at the process boundary and are usually provided by the runtime or platform: loggers, a thread pool, the process’s event loop, an OS handle. Even then, prefer injection of the logger or pool.
Dependency injection as the modern alternative
Section titled “Dependency injection as the modern alternative”Dependency injection (DI): an object receives its collaborators from the outside instead of constructing or looking them up itself. It is the practical application of the Dependency Inversion principle.
# Python: constructor injection, hand-wired at the composition rootclass SmtpMailer: def __init__(self, host: str): self.host = host def send(self, to: str, body: str) -> None: ...
class SignupService: def __init__(self, mailer, users): # dependencies visible in the signature self.mailer, self.users = mailer, users def register(self, email: str) -> None: self.users.add(email) self.mailer.send(email, "Welcome!")
# composition root: the only place that knows concrete classesdef main(): service = SignupService(SmtpMailer("smtp.example.com"), PostgresUsers(dsn="..."))
# test: pass fakes, no patchingclass FakeMailer: def __init__(self): self.sent = [] def send(self, to, body): self.sent.append((to, body))def test_register_sends_welcome(): m = FakeMailer() SignupService(m, InMemoryUsers()).register("a@x.com") assert m.sent == [("a@x.com", "Welcome!")]// TypeScript: the same, with interfaces as the seamsinterface Clock { now(): Date }class SystemClock implements Clock { now() { return new Date(); } }class FixedClock implements Clock { constructor(private d: Date) {} now() { return this.d; } }
class TokenService { constructor(private clock: Clock) {} isExpired(expiry: Date) { return this.clock.now() > expiry; }}Forms of injection: constructor (preferred: dependencies are required and objects are valid after construction), setter/property (optional dependencies; risks partially-built objects), method/parameter (per-call collaborators). Avoid the service locator (container.get(Mailer) called inside business code): it reintroduces hidden dependencies and is a global registry in disguise.
DI containers (Spring and Guice in Java, .NET’s built-in container, NestJS and InversifyJS/tsyringe in TypeScript, dependency-injector or FastAPI’s Depends in Python) automate wiring and lifetime management (singleton scope, per-request scope, transient). Notice the vocabulary: singleton scope in a container gives you the benefit of one instance without the global-access flaw. A container is an optimization for large graphs; for small and medium apps, manual wiring at the composition root is clearer, type-checked and debuggable. Pure-DI (“poor man’s DI”) scales further than most people assume.
Choosing among them
Section titled “Choosing among them”| Need | Reach for |
|---|---|
| Choose concrete type at runtime | Simple factory / registry |
| Swap whole families consistently | Abstract Factory (or a config object of factories) |
| Many optional params, stepwise or validated build | Builder (or kwargs + frozen dataclass) |
| Cheap copy of a configured object | Prototype / replace / structuredClone |
| One shared instance | Composition root + DI, not Singleton |
Pitfalls
Section titled “Pitfalls”- Factory classes wrapping a single constructor with no variation: pure ceremony.
- Builders for objects that have three fields.
- Singletons used as “convenient globals”.
- Deep vs shallow copy confusion in Prototype.
- Containers with magic autowiring that hide the dependency graph and fail at runtime instead of compile time.
Key takeaways
Section titled “Key takeaways”- Creational patterns decouple what you ask for from which concrete class you get.
- Factory Method/simple factories handle runtime type choice; Abstract Factory handles families; Builder handles complex or optional construction; Prototype clones.
- Many of these dissolve into language features: kwargs and dataclasses for Builder, functions for factories,
replacefor Prototype. - Singleton conflates single-instance with global access; the global access creates hidden dependencies, shared mutable state and untestable code.
- Dependency injection (constructor injection at a composition root) gives lifecycle control without globals and makes testing trivial.
Exercises
Section titled “Exercises”- Conceptual. Distinguish dependency inversion, dependency injection and an IoC container.
- Hands-on (Python). Implement
create_parser(path)choosing JSON/YAML/CSV parsers by extension using a registry decorator@register(".json"). How does a third party add a new format without editing your module? - Hands-on (TypeScript). Write a
QueryBuilderthat producesSELECT ... WHERE ... ORDER BY ...with parameter placeholders. Where should validation occur and why must values not be string-concatenated? - Conceptual. A teammate says “make the DB connection a singleton so every module can import it”. List three problems and propose an alternative.
- Hands-on. Take a function that calls
datetime.now()internally and refactor it for deterministic testing using injection.
Solutions (sketch)
- Inversion: principle (depend on abstractions). Injection: technique (pass collaborators in). Container: tool that automates injection and lifetimes.
- The decorator writes into a module-level dict; third parties import the registry and decorate their own parser class.
- Validate in
build(); bind values as parameters to prevent SQL injection (Reliability & Security). - Hidden dependency, shared mutable state across tests, concurrency/lifetime problems (connection pooling per thread/request). Alternative: create a pool in
main, inject a repository. - Accept a
now: Callable[[], datetime]parameter (defaultdatetime.now) or aClockobject.
Further reading
Section titled “Further reading”- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software (1994).
- Eric Freeman and Elisabeth Robson, Head First Design Patterns (2nd ed., 2020).
- Mark Seemann and Steven van Deursen, Dependency Injection: Principles, Practices, and Patterns (2019).
- Martin Fowler, “Inversion of Control Containers and the Dependency Injection pattern” (2004).
- Peter Norvig, “Design Patterns in Dynamic Languages” (1996 slides).
- Joshua Bloch, Effective Java, items on static factories and builders.