Advertisement
Intermediate JavaScript, Design Patterns in JavaScript

What is the Factory pattern, and how does it differ from calling a class constructor directly?

Short answer

A factory is a function that encapsulates the logic for deciding which class/object to instantiate and how, hiding that complexity from the caller — useful when construction logic is conditional or needs to vary at runtime.

Save JavaScript mock interview
Advertisement
AModel answer
A factory is a function that encapsulates the logic for deciding which class/object to instantiate and how, hiding that complexity from the caller — useful when construction logic is conditional or needs to vary at runtime.
function createShape(type) {
  switch (type) {
    case 'circle': return new Circle();
    case 'square': return new Square();
    default: throw new Error('Unknown shape');
  }
}
Real-world example
A UI library's createElement() function that returns different component instances based on a type string.
Likely follow-ups
  • When would you prefer a factory function over exposing the classes directly?
Related topics