Skip to main content
Practice Problems

What is Factory design pattern?

Creates objects without specifying exact class.

Problem

javascript
// Direct instantiation - inflexible const circle = new Circle(5); const square = new Square(10);

Solution - Simple Factory

javascript
class ShapeFactory { static createShape(type, ...args) { switch(type) { case 'circle': return new Circle(...args); case 'square': return new Square(...args); case 'triangle': return new Triangle(...args); default: throw new Error('Unknown shape'); } } } // Usage const shape1 = ShapeFactory.createShape('circle', 5); const shape2 = ShapeFactory.createShape('square', 10);

Real Example - User Roles

javascript
class UserFactory { static createUser(role, data) { switch(role) { case 'admin': return new AdminUser(data); case 'moderator': return new ModeratorUser(data); case 'regular': return new RegularUser(data); default: return new GuestUser(data); } } } // Usage const admin = UserFactory.createUser('admin', { name: 'John' }); admin.deleteUser(); // Only admin can do this

Benefits

✅ Flexibility ✅ Encapsulation ✅ Single place for creation logic ✅ Easy to extend

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems