DEV Community

Vishnu KN
Vishnu KN

Posted on • Edited on

TIL: Factory Design Pattern

In scenarios where the object creation logic is complex or dynamic, the factory design pattern comes in handy.

Imagine someone walking up to, say, a car manufacturing factory, with a request for a car of a certain type (red color, sedan, 818 total horsepower etc) and the factory accepts the request, figures out how to makes it and delivers a concrete product back to the user.

That is the whole idea behind the factory pattern.

So basically, with the factory design pattern, the end result that we want as developers is a way to create objects using a factory class and an abstract instruction like:

objectFactory.createObject(objectType);

So, in order to do something like this, objectFactory should, of necessity, have a static method of the same name.

The reason why it should be static is that we do not want the factory to create a sub-factory and then create the object requested because that would be inefficient

The static method should be very flexible, in the sense that it can take the parameter passed into it and return a concrete instance of an object.

class ObjectFactory {
  static createObject(type) {
    switch (type) {
      case "car":
        return new Car();
      case "bike":
        return new Bike();
      default:
        throw new Error("Invalid object type");
    }
  }
}

class Car {
  drive() {
    console.log("Driving a car");
  }
}

class Bike {
  ride() {
    console.log("Riding a bike");
  }
}

// Usage
const myCar = ObjectFactory.createObject("car");
myCar.drive(); // Output: Driving a car

const myBike = ObjectFactory.createObject("bike");
myBike.ride(); // Output: Riding a bike

Enter fullscreen mode Exit fullscreen mode

The factory pattern is like submitting a token at a glass covered token which is then accepted by a faceless hand which then picks the right model/variant based on the request, quickly builds/assembles the car and hands it back to the requester.

The factory is the factory class. The faceless hand is the static method and the right model/variant that it picks represent the classes it uses to create the object.

You are just saying to the factory - "Here is my request - hand me the appropriate car" and the factory figures out the how and does just that.

Top comments (0)