What It Is
The Factory Method pattern puts the creation of an object behind a function. The caller says what it wants — the factory decides which concrete class to build and returns it as an interface.
The caller never touches the concrete classes, so new kinds can be added without changing any calling code. In TypeScript this is simply a createSomething() function whose return type is the interface.
Example: A Storage Factory
createStorage("disk") and createStorage("memory") return different concrete classes behind the same OrderStorage interface — the caller cannot tell the difference, and does not need to.
The factory picks the class
The switch over kinds lives in one place — the factory. The rest of the program only knows the interface, so the loop calls store.save() without ever asking what it got.
Output: TypeScript file and captured output
interface OrderStorage {
save(data: string): string
}
class DiskStore implements OrderStorage {
save(data: string): string {
return "disk: saved " + data
}
}
class MemoryStore implements OrderStorage {
save(data: string): string {
return "memory: kept " + data
}
}
// The factory decides which concrete class to build.
function createStorage(kind: string): OrderStorage {
switch (kind) {
case "memory":
return new MemoryStore()
default:
return new DiskStore()
}
}
for (const kind of ["disk", "memory"]) {
const store = createStorage(kind)
console.log(store.save("order #1042"))
}
When to Use It
Use it when the concrete class depends on something known only at run time — a config value, a user choice, an environment — or when you want creation logic in exactly one place.
Skip it when there is only one implementation and no sign of a second. const store = new DiskStore() needs no factory.
Pros and Cons
Pros: creation logic in one place; callers depend only on the interface; adding a kind touches only the factory.
Cons: one more layer to read through; with a single implementation it is pure ceremony.