Factory Pattern
In one line
The Factory pattern defines an interface for creating objects without specifying their concrete class at the call site.
In simple words
The Factory pattern lets you create objects without calling a specific class's constructor directly. Instead, you call a factory function or method that decides which concrete class to instantiate based on input. This decouples the calling code from the specific types being created.
For example, a createButton(platform) factory returns a WindowsButton on Windows and a MacButton on macOS. The calling code just says "give me a button" and does not care which concrete class it gets — it works against a common Button interface.
Factories are valuable when creation logic is complex, when you want to centralize object construction, or when the concrete type should be chosen at runtime. They are the foundation of dependency injection and many frameworks.
Example
class Dog { speak() { return "Woof"; } }
class Cat { speak() { return "Meow"; } }
function animalFactory(type) {
if (type === "dog") return new Dog();
if (type === "cat") return new Cat();
throw new Error("Unknown animal");
}
const pet = animalFactory("dog");
console.log(pet.speak()); // WoofanimalFactory decides which class to instantiate. The caller does not know or care whether it gets a Dog or Cat.
Related terms
Related Resources
Related Lessons
- Design Patterns
Factory is a creational pattern.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.