Factory Method Pattern
Delegate object instantiation to a factory method so callers work with an interface rather than concrete classes.
1. Intent
Define an interface for creating an object in a base Creator, but let subclasses or concrete factories decide which Product class to instantiate, keeping callers coupled only to the product interface.
2. Problem
Suppose your service emits structured logs. In local development it writes pretty-printed lines to StdoutExporter. In production it ships JSON batches over gRPC to an OpenTelemetry collector (OtlpExporter), and in CI it writes to a local NDJSON file.
If your telemetry service calls new StdoutExporter() directly—or scatters if (env === 'prod') new OtlpExporter() across five modules—adding a new sink (like Datadog) forces edits everywhere an exporter is constructed.
3. Solution
Extract a LogExporter interface (write(entry), flush()) and move construction into a createExporter() factory method on an abstract ExporterCreator class.
ExporterCreator implements the shared emission workflow (emit(entry)), calling this.createExporter() without knowing which concrete class it gets. Concrete creators (DevExporterCreator, ProdExporterCreator) override createExporter() to return StdoutExporter or OtlpExporter.
Factory Method vs Abstract Factory
| Aspect | Factory Method | Abstract Factory |
|---|---|---|
| Scope | Creates one product per factory method | Creates a family of related products |
| Mechanism | Typically a method overridden in subclasses | An interface with multiple creation methods |
| Example | createExporter() -> LogExporter | CloudFactory.createBlobStore() + createQueue() |
4. Real-world analogy
5. Flow: watch it work
Factory Method: Creator → Product Interface → Concrete
Press Start or tap any step dot to trace the path.
▸All steps (6)
6. Structure
7. Code
interface LogEntry {
level: 'info' | 'error';
message: string;
}
// Product interface
interface LogExporter {
write(entry: LogEntry): Promise<void>;
flush(): Promise<void>;
}
// Concrete Products
class StdoutExporter implements LogExporter {
async write(entry: LogEntry): Promise<void> {
console.log(`[dev:${entry.level}] ${entry.message}`);
}
async flush(): Promise<void> {}
}
class OtlpExporter implements LogExporter {
constructor(private readonly endpoint: string) {}
async write(entry: LogEntry): Promise<void> {
console.log(`[otlp -> ${this.endpoint}] ${JSON.stringify(entry)}`);
}
async flush(): Promise<void> { /* flush gRPC batch */ }
}
// Abstract Creator
abstract class ExporterCreator {
// Factory Method
protected abstract createExporter(): LogExporter;
async emit(entry: LogEntry): Promise<void> {
const exporter = this.createExporter();
await exporter.write(entry);
await exporter.flush();
}
}
// Concrete Creators
class DevExporterCreator extends ExporterCreator {
protected createExporter(): LogExporter {
return new StdoutExporter();
}
}
class ProdExporterCreator extends ExporterCreator {
constructor(private readonly collectorUrl: string) {
super();
}
protected createExporter(): LogExporter {
return new OtlpExporter(this.collectorUrl);
}
}
// Usage
function selectCreator(env: 'dev' | 'prod'): ExporterCreator {
return env === 'prod'
? new ProdExporterCreator('https://otel.internal:4317')
: new DevExporterCreator();
}
const telemetry = selectCreator('prod');
await telemetry.emit({ level: 'info', message: 'Service started' });8. When to use / when to avoid
- You do not know beforehand the exact concrete types your code will need to instantiate.
- You want library or framework users to extend internal components by subclassing a Creator.
- You have shared Creator lifecycle logic (`emit` -> `write` -> `flush`) around an interchangeable product.
- A single plain function `createExporter(env)` solves the branching cleanly with no Creator class hierarchy.
- There is only one concrete product and no second environment or driver in sight.
- You need to create whole families of matching objects together—use Abstract Factory instead.
When NOT to use it
Overengineering happens when you create an AbstractCreator and three ConcreteCreator subclasses just to wrap a single switch (env) that could have been a 5-line createExporter(env) function. Only reach for the full Creator hierarchy when the base Creator carries meaningful shared workflow logic or when external users subclass it.
Real-world example in this stack
In scripts/new.mjs, the scaffolding CLI acts as a template factory: given a kind (note or concept), it selects the matching file in content/_templates/ and stamps out a new MDX page with today's dates.
9. How to implement
Extract a Product interface
Ensure all concrete products (StdoutExporter, OtlpExporter) implement a common LogExporter contract.
Add the factory method to the Creator
Declare createExporter(): LogExporter on the base Creator class.
Replace direct new calls in Creator logic
Have emit() call this.createExporter() instead of instantiating a concrete class.
Implement Concrete Creators per variant
Create DevExporterCreator and ProdExporterCreator (or use a simple factory function if there is no shared Creator behavior).
10. Pros / Cons
- Avoids tight coupling between Creator logic and concrete Product classes.
- Single Responsibility Principle: centralizes product creation in one place.
- Open/Closed Principle: introduce new log exporters without editing existing workflow code.
- Requires creating parallel Creator subclasses if you only wanted to swap one dependency.
- A simple factory function or constructor injection is often cleaner in TypeScript.
11. Relations
Factory Method creates a single product via an overridden method; Abstract Factory creates families of related products via an object interface.
Factory Method is often a specialization of Template Method—a step inside a larger base-class algorithm.
A Factory Method (or Abstract Factory) can instantiate and pair the right Abstraction and Implementation at startup.
12. Check yourself
Check Yourself
1. How does Factory Method differ from Abstract Factory?
2. When is a Factory Method class hierarchy overkill in TypeScript?
Sources
- TypeScript Handbook: Classes
- Refactoring.Guru: Factory Method Pattern
- Dive Into Design Patterns (Alexander Shvets), chapter "Creational Design Patterns: Factory Method"
Dependency Injection in TypeScript
Constructor injection by hand vs DI containers, testing with in-memory fakes, why Service Locator is an anti-pattern, and when DI is overkill.
Adapter Pattern
Wrap incompatible third-party or legacy interfaces behind a single contract your application already expects.