Why use a factory instead of calling new directly?
A factory hides which concrete class is created and how. Callers ask for what they need, and creation rules can change in one place without touching the callers.
Explain it simply
When you order "a ride" in an app, you do not decide whether an auto, a bike or a cab turns up; the app's dispatch picks. A factory is that dispatch for objects.
Example
class Auto { cost(km) { return 30 + 12 * km; } }
class Bike { cost(km) { return 10 * km; } }
class Cab { cost(km) { return 50 + 15 * km; } }
function createRide(type) {
switch (type) {
case "auto": return new Auto();
case "bike": return new Bike();
case "cab": return new Cab();
default: throw new Error("unknown ride: " + type);
}
}
console.log(createRide("auto").cost(5)); // Output: 90
console.log(createRide("bike").cost(5)); // Output: 50
console.log(createRide("cab").cost(5)); // Output: 125Callers know only the cost method and the type name. A new Metro type means editing createRide, not every place that needs a ride.
What to say in the interview
"A factory centralises creation logic and returns objects through a common interface, so callers do not depend on concrete classes. It is useful when the exact class depends on input or configuration, and when creation involves setup steps."
Common mistakes
- Adding a factory for a class that is created in one place and never varies.