0
0
JavascriptConceptBeginner · 3 min read

Factory Pattern in JavaScript: What It Is and How It Works

The factory pattern in JavaScript is a design method that creates objects without specifying the exact class. It uses a function called a factory to make and return different objects based on input or conditions.
⚙️

How It Works

Imagine you want to buy a toy, but instead of going to different stores for each type, you go to one toy factory that makes any toy you ask for. The factory pattern works the same way in programming: you have one function that creates different objects depending on what you need.

This pattern hides the details of how objects are made. You just ask the factory for an object, and it gives you the right one. This makes your code cleaner and easier to change because you don’t have to write the creation logic everywhere.

💻

Example

This example shows a factory function that creates different types of animals based on the input.

javascript
function animalFactory(type) {
  if (type === 'dog') {
    return {
      speak: () => 'Woof!'
    };
  } else if (type === 'cat') {
    return {
      speak: () => 'Meow!'
    };
  } else {
    return {
      speak: () => 'Unknown animal sound'
    };
  }
}

const dog = animalFactory('dog');
const cat = animalFactory('cat');
const unknown = animalFactory('bird');

console.log(dog.speak());
console.log(cat.speak());
console.log(unknown.speak());
Output
Woof! Meow! Unknown animal sound
🎯

When to Use

Use the factory pattern when you need to create many objects that share similar features but differ in some details. It is helpful when the exact type of object is decided during runtime, like creating different user roles, shapes, or animals.

It also helps when you want to keep your code flexible and easy to maintain. Instead of changing many places in your code, you only update the factory function.

Key Points

  • The factory pattern creates objects through a function instead of using new directly.
  • It hides the details of object creation from the user.
  • It makes code easier to maintain and extend.
  • It is useful when object types depend on conditions or inputs.

Key Takeaways

The factory pattern creates objects without exposing creation logic.
It uses a function to return different objects based on input.
It improves code flexibility and maintainability.
Use it when object types vary and depend on runtime conditions.