Sunday, September 5, 2021

Factory design pattern in JavaScript

Must read

The factory pattern is one of the most commonly used design patterns in JavaScript and other languages as well for creating objects. This so-called factory pattern is to individually encapsulate the process of creating objects.

In the factory pattern, we do not expose the creation logic of the application to the client when creating an object, and it is a pattern that uses a common interface to point to the newly created object and replaces the new operation with a factory method.

Let’s Dive into the code

class FactoryClass {
    create_object(name) {
        return new Animal(name)
    }
}

class Animal {
    constructor(name) {
        this.name = name
    }
}

let factoryObject = new FactoryClass()

let dog = factoryObject.create_object('Dog')
console.log(dog.name) // Dog

let cat = factoryObject.create_object('Cat') 
console.log(cat.name) // Cat

Code Summary:

  • We have created a FactoryClass which has a function create_object which further returns the object of the Animal class.
  • The constructor of the Animal class is separated from the create_object function of the FactoryClass, and therefore the new operation is encapsulated.

When will factory pattern be used ?

  • If you do not want a strong coupling in any subsystem and other objects of the subsystem, but want to select from many the subssytems at runtime, then factory pattern in javascript is a perfect choice
  • When we are dependent on a specific environment to create different instances which have the same kind of behavior, then go for factory pattern

Advantages of factory pattren

Let’s take an example:

You go to a restaurant and directly order and consume the food, you do not know how it was made or you did not make it yourself. The person who orders do not pay attention to how his meal was prepared.

The object called outside the factory class is not allowed to care about how the internal constructor is created, we just need to call the factory method to generate an instance.

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article