JavaScript
/Intermediate
Factory Pattern
Definition
A creational design pattern that uses a 'Factory' method/function to create and return new objects without exposing the exact class or constructor logic to the client.
Explain Like I'm New
Imagine you are at a car dealership. You don't need to know how to weld metal or install an engine to get a car. You just tell the dealer 'I want a red SUV', and they build it and hand you the keys. The Factory Pattern is that dealer. It takes simple configuration and spits out complex, fully-formed objects.
Real World Example
Creating different types of Enemies in a game (Orc, Goblin, Dragon). Instead of importing 3 different Classes across your entire codebase, you just call `EnemyFactory.create('goblin')`.
Common Use Cases
- •When object creation logic is complex
- •When you need to create different objects sharing a common interface based on conditions
Interactive Example
class Developer { constructor(name) { this.name = name; this.type = "Dev"; } } class Designer { constructor(name) { this.name = name; this.type = "Designer"; } } // The Factory class EmployeeFactory { create(name, type) { switch(type) { case "dev": return new Developer(name); case "designer": return new Designer(name); default: throw new Error("Unknown Employee Type"); } } } const factory = new EmployeeFactory(); const employees = []; // Clean, simple creation logic without needing to import specific classes everywhere employees.push(factory.create("Alice", "dev")); employees.push(factory.create("Bob", "designer"));
Interview Questions
basic
- Why use a Factory instead of the `new` keyword directly?
intermediate
- How does the Factory pattern relate to polymorphism?
advanced
- What is an Abstract Factory?