Factory Pattern
- In Turkish
- Factory Deseni
In short
The factory pattern is a creational design pattern that moves object creation into a dedicated function or class, so callers never name the concrete class.
What is the factory pattern?
The factory pattern puts the job of creating objects in one place, a factory, instead of scattering new SomeClass() calls across the codebase. Callers ask the factory for an object that fits an interface, and the factory decides which concrete class to build and how to configure it. This keeps the rest of the code independent of specific implementations, which makes it easier to add new ones or swap them out in tests.
The name covers a few related variants. A simple factory is just a function or static method that returns different classes based on its input, often with a switch statement. The factory method pattern from the classic Gang of Four book lets subclasses override a creation method to decide which object to create, and the abstract factory pattern provides an interface for creating whole families of related objects, such as matching buttons and menus for a light or dark theme.
It works like a car rental desk: you ask for a compact car, and the desk hands you whichever compact model is available without you needing to know who built it. Factories are common for choosing a storage backend, payment provider, or logger from configuration, for picking a parser based on file type, and for creating database connections or HTTP clients with the right settings.
The factory pattern is often confused with the builder pattern and with dependency injection. A builder constructs one complex object step by step through a series of method calls, while a factory returns a ready object in one call. Dependency injection is about who supplies an object's dependencies from the outside, and DI containers use factories internally, but a factory on its own doesn't inject anything. Like any pattern, a factory adds indirection, so it is only worth it when there is a real choice between implementations.
Key takeaways
- A factory centralizes object creation behind a single function or class.
- Callers depend on an interface, not on the concrete class being created.
- Variants include the simple factory, the factory method, and the abstract factory.
- A builder assembles one object step by step; a factory returns it in one call.
- Use a factory when there is a real choice between implementations.
Example
interface Storage {
save(key: string, data: string): Promise<void>;
}
class LocalDiskStorage implements Storage { async save() { /* write to disk */ } }
class CloudStorage implements Storage { async save() { /* upload to object storage */ } }
// The factory decides which concrete class to create
function createStorage(kind: "local" | "cloud"): Storage {
return kind === "cloud" ? new CloudStorage() : new LocalDiskStorage();
}
// Callers only know about the Storage interface
const storage = createStorage(process.env.STORAGE === "cloud" ? "cloud" : "local");
await storage.save("report.txt", "Quarterly numbers");Readers ask
What is the difference between a factory method and an abstract factory?
A factory method creates one kind of object and lets subclasses or configuration decide the concrete class. An abstract factory groups several creation methods to produce a family of related objects that are meant to be used together.
What is the difference between the factory and builder patterns?
A factory returns a finished object in a single call and hides which class it chose. A builder lets you construct one complex object step by step, setting options one at a time before calling a final method such as build().
When should you use the factory pattern?
Use it when the exact class to create depends on configuration, input, or environment, or when creation involves setup you don't want repeated everywhere. If there is only ever one implementation, a plain constructor is simpler.
See also
- Design PatternSoftware Architecture, p. 13A design pattern is a proven, reusable solution to a common problem in software design, described as a general template rather than as finished code.
- InterfaceProgramming Fundamentals, p. 29An interface is a named set of method and property signatures that a type promises to provide, without saying how those members are implemented.
- PolymorphismProgramming Fundamentals, p. 45Polymorphism is the ability of code to work with values of different types through one shared interface, with each type supplying its own behavior.
- Dependency InjectionSoftware Architecture, p. 12Dependency injection is a design technique in which an object receives the other objects it needs from the outside instead of creating them itself.
- Strategy PatternSoftware Architecture, p. 44The strategy pattern is a behavioral design pattern that puts interchangeable algorithms behind one interface, so code can switch between them at run time.
- Singleton PatternSoftware Architecture, p. 41The singleton pattern is a creational design pattern that ensures a class has only one instance and provides a single, global point of access to it.
- Builder PatternSoftware Architecture, p. 3The builder pattern builds a complex object step by step through a separate builder object, with named steps instead of a long constructor full of arguments.
Spotted a mistake or something missing on this page?Suggest an edit