Factory Pattern in Node.js

The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. This pattern is particularly useful when a system needs to create multiple instances of objects that share a common theme, without specifying the exact class of object that will be created.

Here’s a simple example demonstrating the Factory Pattern in Node.js. We’ll create a VehicleFactory that can produce different types of vehicles like cars and trucks based on input parameters.

Step 1: Define the Product Interfaces

First, we define the interfaces for the products our factory will create. In this case, it’s a simple Vehicle class with subclasses Car and Truck.

class Vehicle {
constructor(name) {
this.name = name;
}
start() {
throw new Error("Method 'start()' must be implemented.");
}
}
class Car extends Vehicle {
start() {
return ${this.name} car has started.;
}
}
class Truck extends Vehicle {
start() {
return ${this.name} truck has started.;
}
}

Step 2: Implement the Factory

Next, we implement the VehicleFactory class with a static method createVehicle which determines the type of object to create based on the input.

class VehicleFactory {
static createVehicle(type, name) {
switch (type) {
case 'car':
return new Car(name);
case 'truck':
return new Truck(name);
default:
throw new Error('Vehicle type not supported');
}
}
}

Step 3: Use the Factory to Create Objects

Finally, we use the VehicleFactory to create different types of vehicle objects without specifying the exact class.

const myCar = VehicleFactory.createVehicle('car', 'Honda Civic');
console.log(myCar.start()); // Honda Civic car has started.
const myTruck = VehicleFactory.createVehicle('truck', 'Ford F-150');
console.log(myTruck.start()); // Ford F-150 truck has started.

In this example, the VehicleFactory abstracts the instantiation logic and decides which vehicle type to instantiate based on the provided parameters. This pattern is useful for managing and organizing object creation, especially when there are multiple objects or classes involved that share a common interface but have different implementations.