Course contentsShow
← JavaScript
Lesson 1838 of 2,72338. Object-Oriented PatternsFree lesson

The Factory Pattern

Create objects without specifying the exact class, delegating instantiation logic to a factory function.

The Factory Pattern

You'll learn how to use factory functions to create objects without hard-coding their exact type, making your code more flexible.

What Is the Factory Pattern?

The Factory Pattern uses a function to decide which kind of object to create and return. Instead of calling new SomeClass() directly everywhere in your code, you call a factory function that handles the instantiation logic for you.

Think of it like ordering from a restaurant menu. You don't go into the kitchen and assemble your meal yourself—you tell the waiter what you want, and the kitchen decides how to prepare it. The factory is your waiter.

Why Use a Factory?

When you have multiple object types that share similar purposes but differ in details, a factory centralizes the creation logic. This makes it easier to:

  • Switch between different object types based on conditions
  • Hide complex instantiation details
  • Add new types without changing existing code

Basic Example

function createUser(type, name) {
  if (type === 'admin') {
    return {
      name,
      role: 'admin',
      permissions: ['read', 'write', 'delete']
    };
  } else {
    return {
      name,
      role: 'guest',
      permissions: ['read']
    };
  }
}

const admin = createUser('admin', 'Alice');
const guest = createUser('guest', 'Bob');

console.log(admin.permissions); // ['read', 'write', 'delete']
console.log(guest.permissions); // ['read']

The caller doesn't need to know how admins and guests differ—the factory handles that logic.

Key Takeaway: The Factory Pattern delegates object creation to a function, hiding instantiation details and making it easy to create different object types through a unified interface.