DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

The factory pattern

The factory pattern is a creational design pattern that provides an interface for creating instances of a class, but it allows subclasses to alter the type of objects that will be created. In JavaScript, you can implement a factory pattern using functions and object literals. Here's a simple example:

// Product class
class Car {
  constructor(options) {
    this.model = options.model || "Default";
    this.color = options.color || "Default";
  }

  displayInfo() {
    console.log(`Model: ${this.model}, Color: ${this.color}`);
  }
}

// Factory function
function carFactory(options) {
  return new Car(options);
}

// Usage
const car1 = carFactory({ model: "Toyota", color: "Blue" });
const car2 = carFactory({ model: "Honda", color: "Red" });

car1.displayInfo(); // Output: Model: Toyota, Color: Blue
car2.displayInfo(); // Output: Model: Honda, Color: Red

Enter fullscreen mode Exit fullscreen mode

In this example:

We have a Car class representing the product we want to create.
The carFactory function is a factory function that takes options and returns a new instance of the Car class.
The carFactory function allows us to create different instances of Car with various options.
This simple example demonstrates the basic concept of a factory pattern. In more complex scenarios, you might have different types of products (classes) and a factory function that determines which type of product to create based on certain conditions or input parameters. The factory pattern is often used in conjunction with other design patterns to create flexible and maintainable code.

Top comments (0)