Factory Pattern: Who Should Create Objects?
Factory patterns are more than a way to hide object construction. Learn the differences between Simple Factory, Factory Method, and Abstract Factory, how they work with Dependency Injection, and when each approach makes software easier to maintain.
Table of Contents
- Introduction
- 1. Object Creation Is a Design Responsibility
- 2. Simple Factory: Centralizing Creation Decisions
- 3. Factory Method: Letting Subclasses Decide What to Create
- 4. Abstract Factory: Creating Families of Related Objects
- 5. Comparing the Three Approaches
- 6. Factory and Dependency Injection Are Not the Same
- 7. When a Factory Is Worth the Cost
- 8. Common Factory Design Mistakes
- Summary
Introduction
Creating an object is easy.
In TypeScript, you can instantiate a class with new, pass its dependencies, and start using it. For a small application, this is often all you need.
The design becomes more complicated when object creation involves decisions.
A component may need to choose an implementation based on configuration, construct different groups of related objects, initialize external resources, or manage dependencies that vary between environments. If every part of the application makes these decisions independently, object creation becomes scattered throughout the codebase.
Consider a notification service that supports email and SMS.
class NotificationService {
async send(
channel: string,
recipient: string,
message: string,
): Promise<void> {
if (channel === "email") {
const sender = new EmailSender();
await sender.send(recipient, message);
} else if (channel === "sms") {
const sender = new SmsSender();
await sender.send(recipient, message);
} else {
throw new Error("Unsupported notification channel");
}
}
}This implementation works, but the service is responsible for two separate concerns:
- Sending notifications.
- Deciding which concrete object to create.
As the application grows, similar construction logic may appear in controllers, background workers, scheduled jobs, and other services.
The question is not whether new is bad. It is not.
The question is:
When should a component create its own dependencies, and when should that responsibility belong somewhere else?
Factory patterns help answer this question. However, the term Factory Pattern refers to several related approaches that solve different problems. Understa
1. Object Creation Is a Design Responsibility
Before introducing a factory, identify the actual problem.
Suppose an application supports multiple notification providers. The application should depend on a stable contract rather than require every caller to know how each provider is constructed.
Start with a shared interface:
interface NotificationSender {
send(
recipient: string,
message: string,
): Promise<void>;
}Concrete implementations provide the actual behavior:
class EmailSender implements NotificationSender {
async send(
recipient: string,
message: string,
): Promise<void> {
// Send an email through the configured provider.
}
}
class SmsSender implements NotificationSender {
async send(
recipient: string,
message: string,
): Promise<void> {
// Send an SMS through the configured provider.
}
}The service can now depend on the interface:
class NotificationService {
constructor(
private readonly sender: NotificationSender,
) {}
async send(
recipient: string,
message: string,
): Promise<void> {
await this.sender.send(recipient, message);
}
}The service no longer needs to know which provider it uses.
But someone still needs to create the sender and decide which implementation to supply.
That responsibility has not disappeared. It has moved outside the service.
This distinction is fundamental: abstraction defines what a component needs; a factory can determine how the appropriate object is created.
Whether that separation deserves a dedicated factory depends on the complexity and reuse of the creation logic.
2. Simple Factory: Centralizing Creation Decisions
A Simple Factory centralizes the decision about which concrete object to instantiate.
It is commonly implemented as a function or class. It is a useful design technique, although it is not one of the three classic GoF patterns under that exact name.
For the notification example:
type NotificationChannel = "email" | "sms";
class NotificationSenderFactory {
static create(
channel: NotificationChannel,
): NotificationSender {
switch (channel) {
case "email":
return new EmailSender();
case "sms":
return new SmsSender();
}
}
}Callers can use the factory without knowing the concrete implementation:
const sender = NotificationSenderFactory.create("email");
const service = new NotificationService(sender);
await service.send(
"[email protected]",
"Your order has shipped.",
);The creation decision now lives in one place.
If the application introduces another notification channel, the factory becomes the central location to update.
What problem does this solve?
Without a factory, the same selection logic might be repeated across multiple callers.
// Controller
const sender = channel === "email"
? new EmailSender()
: new SmsSender();
// Background worker
const sender = channel === "email"
? new EmailSender()
: new SmsSender();This duplication creates multiple places where the application must understand the available implementations.
A Simple Factory consolidates that knowledge.
It can also hide construction details when creating an object requires several steps, provided those steps genuinely belong to the factory's responsibility.
What does it not solve?
The factory still needs to know about the concrete implementations.
When adding a new channel, the factory's selection logic must change. That is not necessarily a problem: a small, stable selection point can be perfectly reasonable.
Also, a factory that only wraps a single new expression may add no meaningful value.
Compare:
const sender = new EmailSender();with:
const sender = NotificationSenderFactory.create("email");If the factory does nothing except return new EmailSender(), it may be unnecessary indirection.
Use a Simple Factory when centralizing creation decisions makes the code easier to maintain—not simply because object creation exists.
3. Factory Method: Letting Subclasses Decide What to Create
Factory Method addresses a different problem.
Instead of one central factory deciding which implementation to instantiate, a base class defines a creation method, and subclasses override that method to provide the appropriate product.
This approach is useful when a workflow should remain consistent while the concrete object used by that workflow varies.
Imagine an application that processes notifications through different delivery channels. The overall workflow includes preparing a message and sending it, but the concrete sender depends on the processor.
A Factory Method design could look like this:
interface NotificationSender {
send(
recipient: string,
message: string,
): Promise<void>;
}
abstract class NotificationProcessor {
async process(
recipient: string,
message: string,
): Promise<void> {
const sender = this.createSender();
await sender.send(recipient, message);
}
protected abstract createSender(): NotificationSender;
}The base class defines the workflow. Subclasses decide which sender the workflow uses.
class EmailNotificationProcessor
extends NotificationProcessor {
protected createSender(): NotificationSender {
return new EmailSender();
}
}
class SmsNotificationProcessor
extends NotificationProcessor {
protected createSender(): NotificationSender {
return new SmsSender();
}
}Usage:
const processor = new EmailNotificationProcessor();
await processor.process(
"[email protected]",
"Your order has shipped.",
);The base workflow does not need to know the concrete sender class.
Why use inheritance here?
The purpose is to let a subclass specialize one part of a workflow without rewriting the workflow itself.
This is a form of the Template Method approach to designing an algorithm: the base class defines the overall sequence, while a creation method provides a customization point.
Factory Method and Template Method are related but not identical concepts. In this example, createSender() is the factory method, and process() is the stable workflow that uses it.
What is the trade-off?
This design introduces inheritance and additional classes.
If the application only needs to choose between two senders based on a configuration value, a Simple Factory or dependency injection may be much simpler.
Factory Method is more appropriate when subclass-specific creation is a meaningful part of an extensible workflow.
Do not introduce inheritance solely to avoid a switch statement.
4. Abstract Factory: Creating Families of Related Objects
Abstract Factory addresses a third problem.
Sometimes an application does not need just one interchangeable object. It needs a family of related objects that must work together.
Consider a product that supports two cloud providers. Each provider has its own storage client and messaging client.
The application needs to ensure that components configured for one provider are used together, rather than accidentally mixing incompatible implementations.
Define the product interfaces:
interface StorageClient {
upload(
key: string,
content: Uint8Array,
): Promise<void>;
}
interface MessageClient {
publish(
topic: string,
message: string,
): Promise<void>;
}Now define an abstract factory that creates both products:
interface CloudProviderFactory {
createStorage(): StorageClient;
createMessaging(): MessageClient;
}A provider-specific factory implements the family of products.
class AwsStorageClient implements StorageClient {
async upload(
key: string,
content: Uint8Array,
): Promise<void> {
// Upload through the configured AWS storage service.
}
}
class AwsMessageClient implements MessageClient {
async publish(
topic: string,
message: string,
): Promise<void> {
// Publish through the configured AWS messaging service.
}
}
class AwsProviderFactory implements CloudProviderFactory {
createStorage(): StorageClient {
return new AwsStorageClient();
}
createMessaging(): MessageClient {
return new AwsMessageClient();
}
}Another factory could provide the corresponding implementations for a different cloud platform:
class AzureStorageClient implements StorageClient {
async upload(
key: string,
content: Uint8Array,
): Promise<void> {
// Upload through the configured Azure storage service.
}
}
class AzureMessageClient implements MessageClient {
async publish(
topic: string,
message: string,
): Promise<void> {
// Publish through the configured Azure messaging service.
}
}
class AzureProviderFactory implements CloudProviderFactory {
createStorage(): StorageClient {
return new AzureStorageClient();
}
createMessaging(): MessageClient {
return new AzureMessageClient();
}
}The application can now receive one provider factory:
class DocumentService {
private readonly storage: StorageClient;
private readonly messaging: MessageClient;
constructor(factory: CloudProviderFactory) {
this.storage = factory.createStorage();
this.messaging = factory.createMessaging();
}
async storeDocument(
key: string,
content: Uint8Array,
): Promise<void> {
await this.storage.upload(key, content);
await this.messaging.publish(
"documents-stored",
key,
);
}
}The application chooses a provider family at its composition boundary:
const providerFactory = new AwsProviderFactory();
const documentService = new DocumentService(providerFactory);The service does not need to know how to construct AWS or Azure clients.
Why not use two independent factories?
You could create a storage client and a messaging client separately. That may be appropriate if those choices are genuinely independent.
Abstract Factory is valuable when the products form a meaningful family and the application benefits from selecting them together.
For example, a provider factory can help ensure that storage and messaging are configured for the same cloud environment.
However, the interfaces alone do not guarantee compatibility. If the implementations are misconfigured or depend on incompatible resources, additional validation and integration tests are still necessary.
What is the trade-off?
Abstract Factory introduces multiple interfaces and concrete factory implementations.
It also makes adding a new product type more involved: each concrete factory may need to implement the new creation method.
This is a reasonable trade-off when the application regularly switches between related product families. It is excessive when only one or two unrelated dependencies need to be created.
5. Comparing the Three Approaches
Although all three approaches involve object creation, their intent differs.
| Approach | Main problem | Typical mechanism |
|---|---|---|
| Simple Factory | Creation decisions are scattered or becoming complex | Function or class that selects an implementation |
| Factory Method | A subclass must customize which product a workflow creates | Overridable creation method |
| Abstract Factory | Related objects must be created as a compatible family | Factory interface that creates multiple product types |
A useful way to distinguish them is to ask three questions:
Simple Factory: Where should this creation decision live?
Factory Method: How can a subclass customize object creation without changing the overall workflow?
Abstract Factory: How can the application create a consistent family of related objects?
These approaches are not necessarily mutually exclusive. A system may use an Abstract Factory for provider-specific clients and Simple Factory logic for choosing which provider factory to initialize.
The goal is not to use all three. The goal is to choose the smallest design that addresses the actual creation problem.
6. Factory and Dependency Injection Are Not the Same
Factory and Dependency Injection are often discussed together because both affect how components obtain their dependencies.
However, they answer different questions.
A factory answers:
How should an object be created?
Dependency Injection answers:
How should a component receive the dependencies it needs?
Consider this service:
class ReportService {
constructor(
private readonly storage: StorageClient,
) {}
async save(
key: string,
content: Uint8Array,
): Promise<void> {
await this.storage.upload(key, content);
}
}ReportService receives a StorageClient. It does not construct one or decide which provider to use.
That is dependency injection, regardless of whether the dependency came from a factory, a dependency injection container, or a manually written composition function.
For example, manual composition is sufficient:
const storage = new AwsStorageClient();
const reportService = new ReportService(storage);A factory may be useful if construction is more involved:
const storage = storageFactory.createStorage();
const reportService = new ReportService(storage);A dependency injection container may be appropriate when an application has many dependencies, scopes, or lifecycle rules.
But a container is not a prerequisite for dependency injection, and a factory is not a prerequisite for either.
You can use dependency injection without a factory. You can use a factory without a dependency injection container. You can also combine them when their separate responsibilities justify doing so.
The design should reflect the application's actual complexity.
7. When a Factory Is Worth the Cost
A factory is most valuable when it centralizes a meaningful creation responsibility.
Common situations include:
- Multiple implementations: A configuration or runtime decision determines which implementation to construct.
- Complex initialization: Creating an object requires coordinated setup or validation.
- Repeated construction rules: Multiple components need the same creation logic.
- Environment-specific dependencies: Tests, development, and production need different implementations.
- Related product families: Several objects must be selected or configured together.
- Plugin systems: Implementations are registered and created based on a key or capability.
Not every situation requires the same factory style.
A small function may be enough for selecting an implementation. A Factory Method may suit an inheritance-based extension point. Abstract Factory may be justified when an application needs consistent families of related products.
Consider the simplest approach first.
Prefer direct construction when the dependency is obvious
const service = new ReportService(
new AwsStorageClient(),
);This is easy to read when there is one implementation and no meaningful construction complexity.
Prefer a small factory when selection is repeated
If several components independently interpret the same provider configuration, a centralized factory can reduce duplication and keep selection rules consistent.
Prefer Abstract Factory when products belong together
If switching providers means replacing several related implementations as a unit, an Abstract Factory can make that relationship explicit.
The right design is the one that makes object creation easier to understand and change without adding unnecessary indirection.
8. Common Factory Design Mistakes
Creating a factory for every class
A class does not automatically need a factory just because it can be instantiated.
Excessive factories add files, interfaces, and navigation without necessarily reducing coupling.
Use a factory when creation itself is a responsibility worth isolating.
Building a factory that knows everything
A factory can become a new source of coupling if it imports every implementation, manages unrelated business rules, and handles initialization for the entire application.
Keep its responsibility focused on constructing the products it owns.
Confusing object creation with business logic
A factory may decide which implementation to instantiate, but it should not automatically absorb unrelated business decisions.
For example, determining whether a payment requires additional verification is not necessarily a factory responsibility. That decision belongs wherever the relevant business policy is defined.
Assuming factories eliminate conditional logic
A factory often centralizes a conditional rather than removing it.
This can still be a meaningful improvement if the conditional now lives in one appropriate location. Do not measure design quality by the number of if statements.
Using Abstract Factory for unrelated dependencies
Abstract Factory is useful when multiple products form a family. Grouping unrelated dependencies behind one factory simply because they are created in the same place can obscure rather than clarify the design.
The relationship between products should be meaningful.
Ignoring object lifecycle
Creating an object is not the same as managing its lifecycle.
A factory may return a new instance on every call, return a shared instance, or delegate to another component that manages resources. Those choices affect connection pools, memory, cleanup, and concurrency.
Make lifecycle behavior explicit when it matters, especially for database connections, network clients, and other resource-heavy dependencies.
Summary
Factory patterns are not primarily about hiding the new keyword. They are about deciding where object creation belongs and how much of that responsibility should be separated from the rest of the application.
A Simple Factory centralizes creation decisions. Factory Method lets subclasses customize product creation within a stable workflow. Abstract Factory creates families of related objects through a common contract.
Dependency Injection complements these patterns by separating a component's dependencies from the way it obtains them.
Before introducing a factory, ask:
- Is object creation complex or repeated?
- Does choosing an implementation belong inside this component?
- Are multiple related objects required to work together?
- Will a factory reduce coupling or simply add another layer?
- Is the chosen design simpler than direct construction?
If direct construction is clear and stable, keep it.
If creation decisions are scattered, centralize them. If subclasses need to customize a workflow's product, consider Factory Method. If related implementations must be created as a family, consider Abstract Factory.
Good object creation design is not about hiding construction. It is about making the decisions, dependencies, and lifecycle of objects explicit and manageable.
- Design Patterns
- Factory Pattern
- OOP
- Programing
- Software Architecture