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
Loading Code Playground...
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?