Create Objects Flexibly with the Factory Pattern
How to use factory methods, abstract factories, and dependency injection containers to decouple object creation from usage and improve testability.
Overview
Nothing beats new DatabaseConnection("postgres://...") for simplicity — and nothing locks you in harder. Whoever calls that constructor knows the exact class, its signature, and every dependency it needs. Swap the database driver and you’re editing every call site. If the connection needs a pool instead of a direct connection, every new statement breaks. If you want to test the caller with a mock database, you can’t — the new keyword hardcodes the concrete class.
The factory pattern moves object creation into a dedicated method or class. Instead of calling a constructor, the caller asks the factory for an object — and the factory alone decides which concrete class to build, how its dependencies get wired, and which defaults apply. The caller depends on an abstraction — an interface or abstract class — not a concrete implementation. Below you’ll find working implementations of the three common variants — factory method, abstract factory, and simple factory — in TypeScript, Java, and Python, plus the patterns teams reach for once a manual factory stops scaling.
When to use it
Use this recipe when:
- The exact class of the object is determined at runtime from configuration or input — a notification channel read from
NOTIFY_BY, a payment provider chosen per tenant. - Building the object takes real initialization work — connection pools, caches, event listeners. See Singleton Pattern for managing shared instances.
- Tests need to substitute real implementations with mocks or stubs. See Unit Testing with Mocks for the mechanics.
- Creating objects directly would violate dependency inversion — high-level modules depend on low-level details. See Hexagonal Architecture for how ports and adapters formalize this.
- You’re building a framework or library where users plug in their own implementations.
A quick litmus test: if you find new calls scattered across business logic and changing a constructor signature forces edits in a dozen files, a factory pays for itself. If a constructor has two arguments and never changes, new is fine — don’t add indirection you don’t need.
Solution
Factory Method (TypeScript)
interface Notifier {
send(message: string, recipient: string): Promise<void>;
}
class EmailNotifier implements Notifier {
constructor(private smtpHost: string, private from: string) {}
async send(message: string, recipient: string): Promise<void> {
// SMTP implementation
console.log(`Email to ${recipient}: ${message}`);
}
}
class SmsNotifier implements Notifier {
constructor(private twilioSid: string) {}
async send(message: string, recipient: string): Promise<void> {
// Twilio implementation
console.log(`SMS to ${recipient}: ${message}`);
}
}
abstract class NotificationFactory {
abstract createNotifier(): Notifier;
async notifyUser(message: string, recipient: string): Promise<void> {
const notifier = this.createNotifier();
await notifier.send(message, recipient);
}
}
class EmailNotificationFactory extends NotificationFactory {
createNotifier(): Notifier {
return new EmailNotifier(process.env.SMTP_HOST!, 'noreply@example.com');
}
}
class SmsNotificationFactory extends NotificationFactory {
createNotifier(): Notifier {
return new SmsNotifier(process.env.TWILIO_SID!);
}
}
// Usage
const factory: NotificationFactory = process.env.NOTIFY_BY === 'sms'
? new SmsNotificationFactory()
: new EmailNotificationFactory();
await factory.notifyUser('Your order has shipped!', 'user@example.com');
Abstract Factory (Java)
// Abstract product interfaces
interface Button {
void render();
}
interface Checkbox {
void check();
}
// Concrete products for Windows
class WindowsButton implements Button {
public void render() { System.out.println("Rendering Windows button"); }
}
class WindowsCheckbox implements Checkbox {
public void check() { System.out.println("Checking Windows checkbox"); }
}
// Concrete products for macOS
class MacButton implements Button {
public void render() { System.out.println("Rendering Mac button"); }
}
class MacCheckbox implements Checkbox {
public void check() { System.out.println("Checking Mac checkbox"); }
}
// Abstract factory
interface UIFactory {
Button createButton();
Checkbox createCheckbox();
}
// Concrete factories
class WindowsUIFactory implements UIFactory {
public Button createButton() { return new WindowsButton(); }
public Checkbox createCheckbox() { return new WindowsCheckbox(); }
}
class MacUIFactory implements UIFactory {
public Button createButton() { return new MacButton(); }
public Checkbox createCheckbox() { return new MacCheckbox(); }
}
// Application
class Application {
private final Button button;
private final Checkbox checkbox;
Application(UIFactory factory) {
this.button = factory.createButton();
this.checkbox = factory.createCheckbox();
}
void renderUI() {
button.render();
checkbox.check();
}
}
// Usage
UIFactory factory = System.getProperty("os.name").contains("Windows")
? new WindowsUIFactory()
: new MacUIFactory();
new Application(factory).renderUI();
Simple Factory (Python)
import os
from typing import Protocol
class PaymentProcessor(Protocol):
def charge(self, amount: float, currency: str) -> dict:
...
class StripeProcessor:
def __init__(self, api_key: str):
self.api_key = api_key
def charge(self, amount: float, currency: str) -> dict:
return {"provider": "stripe", "status": "success", "amount": amount}
class PayPalProcessor:
def __init__(self, client_id: str, secret: str):
self.client_id = client_id
self.secret = secret
def charge(self, amount: float, currency: str) -> dict:
return {"provider": "paypal", "status": "success", "amount": amount}
class PaymentProcessorFactory:
def create(self, provider: str) -> PaymentProcessor:
if provider == "stripe":
return StripeProcessor(api_key=os.environ["STRIPE_API_KEY"])
elif provider == "paypal":
return PayPalProcessor(
client_id=os.environ["PAYPAL_CLIENT_ID"],
secret=os.environ["PAYPAL_SECRET"],
)
else:
raise ValueError(f"Unknown provider: {provider}")
# Usage
factory = PaymentProcessorFactory()
processor = factory.create("stripe")
result = processor.charge(99.99, "USD")
Explanation
- Factory method: a method that subclasses override to decide which object gets instantiated. The base class owns the algorithm (
notifyUser); the subclass owns the creation choice. The base class depends on theNotifierinterface, never onEmailNotifierorSmsNotifier. - Abstract factory: a coordinated set of factories for related products.
WindowsUIFactoryhands out aWindowsButtonand aWindowsCheckboxbuilt to the same theme, so changing themes is a matter of swapping one factory instead of chasing down scattered instantiations. The guarantee you’re paying for is consistency across the family. - Simple factory: one function or class that builds objects from a parameter. Strictly speaking it isn’t a GoF pattern, yet it’s what most “factories” in production code actually are — creation logic in one place, without the deeper dependency inversion of the other two.
- Dependency injection: at scale, even the factories get created by something else — a DI container (Spring, Angular, InversifyJS). You declare bindings like
Notifier→EmailNotifierin one place and the container walks the dependency graph for you. The factory stops being application code and turns into configuration.
The trade-off is always the same: you buy decoupling and testability at the cost of an extra layer of indirection. That indirection is worth it when implementations change, multiply, or need mocking — and dead weight when they don’t.
Variants
| Pattern | Level of abstraction | Best for | Complexity |
|---|---|---|---|
| Simple factory | Low | Single creator with runtime type | Low |
| Factory method | Medium | Template method with customizable creation | Medium |
| Abstract factory | High | Families of related objects | Medium-High |
| Builder | High | Complex objects with many optional parameters | Medium |
| DI container | Highest | Enterprise applications with deep dependency graphs | High |
Choosing between them is mostly about who needs to vary. If only the concrete class varies, a simple factory is enough. If the creation process varies per subclass — each subclass picks its own product — use factory method. If entire families of objects must stay consistent (a Windows theme can’t mix with macOS widgets), that’s abstract factory territory. And when you’re no longer choosing implementations in code but declaring them in configuration, you’ve outgrown manual factories and want a DI container.
Advanced Variants
DI Container with Factory Providers (TypeScript)
interface Container {
bind<T>(token: string, factory: () => T): void;
resolve<T>(token: string): T;
}
class SimpleContainer implements Container {
private bindings: Map<string, () => unknown> = new Map();
private instances: Map<string, unknown> = new Map();
bind<T>(token: string, factory: () => T): void {
this.bindings.set(token, factory);
}
resolve<T>(token: string): T {
if (this.instances.has(token)) {
return this.instances.get(token) as T;
}
const factory = this.bindings.get(token);
if (!factory) throw new Error(`No binding for ${token}`);
const instance = factory() as T;
this.instances.set(token, instance);
return instance;
}
}
// Configuration
const container = new SimpleContainer();
container.bind('Logger', () => new ConsoleLogger());
container.bind('Database', () => new PostgresConnection(process.env.DATABASE_URL));
container.bind('UserRepository', () => {
const db = container.resolve<PostgresConnection>('Database');
const logger = container.resolve<ConsoleLogger>('Logger');
return new UserRepository(db, logger);
});
container.bind('UserService', () => {
const repo = container.resolve<UserRepository>('UserRepository');
return new UserService(repo);
});
// Usage — resolve dependencies anywhere
const userService = container.resolve<UserService>('UserService');
await userService.createUser({ email: 'user@example.com', name: 'Alice' });
Factory + Builder (TypeScript)
class PushNotifier implements Notifier {
constructor(private fcmKey: string) {}
async send(message: string, recipient: string): Promise<void> {
console.log(`Push to ${recipient}: ${message}`);
}
}
// Wraps any Notifier with timeout, retry, and priority policies
class ResilientNotifier implements Notifier {
constructor(
private inner: Notifier,
private timeout: number,
private retries: number,
private priority: string,
) {}
async send(message: string, recipient: string): Promise<void> {
for (let attempt = 0; attempt <= this.retries; attempt++) {
try {
return await this.inner.send(message, recipient);
} catch {
if (attempt === this.retries) throw new Error('Send failed');
}
}
}
}
class NotificationBuilder {
private channel: 'email' | 'sms' | 'push' = 'email';
private timeout: number = 30;
private retries: number = 3;
private priority: 'low' | 'normal' | 'high' = 'normal';
withChannel(channel: 'email' | 'sms' | 'push'): this {
this.channel = channel;
return this;
}
withTimeout(seconds: number): this {
this.timeout = seconds;
return this;
}
withRetries(count: number): this {
this.retries = count;
return this;
}
withPriority(priority: 'low' | 'normal' | 'high'): this {
this.priority = priority;
return this;
}
build(): Notifier {
const base = this.channel === 'email'
? new EmailNotifier(process.env.SMTP_HOST!, 'noreply@example.com')
: this.channel === 'sms'
? new SmsNotifier(process.env.TWILIO_SID!)
: new PushNotifier(process.env.FCM_KEY!);
return new ResilientNotifier(base, this.timeout, this.retries, this.priority);
}
}
// Usage — factory decides which class, builder configures it
const notifier = new NotificationBuilder()
.withChannel('sms')
.withTimeout(10)
.withRetries(5)
.withPriority('high')
.build();
await notifier.send('Server down!', 'admin@example.com');
Async Factory with Connection Pooling (Python)
import asyncio
import asyncpg
from typing import Optional
class DatabaseConnectionFactory:
_pool: Optional[asyncpg.Pool] = None
_lock = asyncio.Lock()
@classmethod
async def create(cls, config: dict) -> 'DatabaseConnection':
if cls._pool is None:
async with cls._lock:
if cls._pool is None:
cls._pool = await asyncpg.create_pool(
dsn=config['url'],
min_size=config.get('min_pool', 5),
max_size=config.get('max_pool', 20),
command_timeout=config.get('timeout', 30),
)
return DatabaseConnection(await cls._pool.acquire())
@classmethod
async def close(cls) -> None:
if cls._pool:
await cls._pool.close()
cls._pool = None
class DatabaseConnection:
def __init__(self, conn):
self._conn = conn
async def query(self, sql: str, *args) -> list:
return await self._conn.fetch(sql, *args)
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self._conn.close()
# Usage — async factory with connection pooling
async def main():
config = {'url': 'postgresql://localhost/mydb', 'max_pool': 10}
async with await DatabaseConnectionFactory.create(config) as db:
users = await db.query('SELECT * FROM users WHERE active = $1', True)
await DatabaseConnectionFactory.close()
What Works
- Return abstractions, not concretions: a factory method should return
Notifier, notEmailNotifier. That lets callers treat every product uniformly and swap implementations freely. Return a concrete type and the factory gives you nothing but ceremony. - Keep factories stateless: a factory creates and returns objects — it shouldn’t hold application state. Stateful factories are awkward to test and obscure object lifetimes; configuration belongs in parameters, not fields.
- Use DI containers for complex graphs: when a service needs a repository, which needs a connection pool, which needs a config loader, wiring factories by hand gets tedious fast. Declare the bindings once and let the container resolve the transitive dependencies.
- Don’t overuse for trivial objects: a factory for a
Dateor aPointwith two coordinates is over-engineering.newis fine for simple value objects. Save factories for things with dependencies, configuration, or runtime polymorphism. - Document the contract, not the factory: consumers need to know what the returned object does — its methods, invariants, thread safety — not how it was built. Document the interface and let the factory stay an implementation detail.
Common mistakes
- God factory: a single factory responsible for every object in the app. It grows to hundreds of lines and breaks single responsibility. Split factories along domain or layer boundaries —
NotificationFactory,PaymentFactory,RepositoryFactory. - Factory doing business logic: a factory creates objects; it doesn’t validate business rules, fire side effects, or orchestrate workflows. If your factory checks whether the user has permission before creating a notifier, that check belongs in a service.
- Ignoring the disposal lifecycle: factories create objects but rarely manage their destruction. If a factory holds references to what it creates, it becomes a memory leak. Use scopes (singleton, request, transient) and clean up on shutdown.
- Hardcoding configuration:
new DatabaseConnection("postgres://localhost")bakes config into code. Inject configuration so the same factory works in development, staging, and production untouched.
See Also
- Factory Pattern — the canonical GoF reference with UML structure and consequences.
- Abstract Factory Pattern — when families of related objects must stay consistent.
- Builder Pattern — for objects with many optional parameters.
- Companion repository — runnable versions of every example in this recipe.
- Gamma et al., Design Patterns (1994) — the original Factory Method and Abstract Factory chapters.
Frequently Asked Questions
When should I use a factory vs a DI container?
A factory is the right tool when creation stays inside one module; a DI container earns its keep when dependencies span the whole app. In practice frameworks blur the line — their containers run on factory providers internally.
Is the factory pattern still relevant with DI frameworks?
Yes — DI frameworks themselves run on factories under the hood. Custom creation logic still lands in factory methods, like picking a database shard from a tenant ID: DI does the wiring, the factory does the deciding.
How do I test code that uses factories?
Swap in a fake factory. When OrderService takes a PaymentProcessorFactory, hand it a stub returning a canned processor — or skip the factory entirely and inject the processor through the constructor in tests.
Can I combine factory with builder?
Yes — they pair naturally. Let the factory pick the class, then let a builder configure that instance: factory.create("email").withTimeout(30).withRetries(3).
What's the difference between factory method and abstract factory?
Factory method is a single overridable method producing one object — the subclass picks which. Abstract factory is an entire interface whose methods produce a family of related objects. One product type? Stay with factory method; it's simpler.
Related Resources
Factory Pattern
Create objects without specifying the exact class to instantiate. A creational design pattern for flexible object creation.
PatternAbstract Factory Pattern
Create families of related objects without specifying concrete classes. A creational design pattern for consistent object families.
PatternBuilder Pattern: Step-by-Step Object Construction
Construct complex objects step by step. A creational design pattern for readable, configurable object construction.
PatternSingleton Pattern: Java, Python & TypeScript Examples
Ensure a class has only one instance and provide global access to it — the creational design pattern for controlled object creation, with production-ready implementations.
RecipeBuild Maintainable Applications with Hexagonal Architecture
Structure applications with ports and adapters to isolate business logic from frameworks, databases, and external services for easier testing.
RecipeWrite Unit Tests with Mocks and Stubs
How to isolate code under test using mock objects, stubs, and spies to replace external dependencies like databases, APIs, and file systems.