Factory Design Pattern in JavaScript

Factory Design Pattern in JavaScript

Design patterns are divided into three categories: creational patterns, structural patterns, and behavioral patterns.

Factory design patterns come under creational patterns and provide object creation mechanisms that promote flexibility and reusability of the code, especially in situations where we want to create many different objects.

Let's take a real-world example of a factory where many products are created. In the case of programming, factory is an object where many other frequently used objects are created.

Factory allows you to handle all the object creation in a centralized location which helps the code clean, concise, and maintainable. Factory methods are frequently used in applications that manage, maintain, or manipulate collections of objects that are different but at the same time have many characteristics (i.e. methods and properties) in common. 

Let us dive deep into the Factory design pattern with an example.

function Developer(name)
{
    this.name = name;
    this.department = "R&D";
    this.role = "Developer";   
}

function Tester(name)
{
    this.name = name;
    this.department = "R&D";
    this.role = "Tester";
}

function Factory()
{
    this.create = (name, type) => {
        switch (type) {
            case 1:
                return new Developer(name);
                break;
            case 2:
                return new Tester(name);
                break;
        }
    }
}

function say(){
    console.log(this.name+" is a "+this.role+" in "+this.department+" department");
}

const factory = new Factory();
const teamMembers = [];

teamMembers.push(factory.create("John", 1));
teamMembers.push(factory.create("Leo", 2));

teamMembers.forEach((member)=>{
    say.call(member);
});

Output:

John is a Developer in R&D department
Leo is a Tester in R&D department

In the above example, there are two types of employees (Developer and Tester) are created. These two objects share some common properties and the main difference is only with role property. So we created another object factory for creating developer and tester objects. It eliminates repeated constructor calls with the new operator for new objects. 

The factory pattern shines if the object creation process involves dynamic factors. In our example dynamic factor is role.

When To Use A Factory Pattern

  • When the object creation process involves a high level of complexity
  • When we need to return different instances of an object depending on some dynamic factors
  • When a class can’t determine the subclass it must create
  • When we need to create different small objects that share some properties

Pros of the factory pattern

  • Promotes loose decoupling by separating the object creation from its implementation
  • Enables us to create different instances based on conditions
  • Promotes code reusability and maintainability
  • Encapsulates the constructor or class and exposes only a defined interface

Cons of the factory pattern

  • Depending on the complexity it can be difficult to test because of the level of abstraction it introduces

 

Related Blogs

pm2 cluster

Scaling Node.js Applications With PM2 Clusters

Learn cluster modules in node js, install and configure PM2 in production, and implement PM2 clusters using the PM2 ecosystem without any modification in the current application code.

call-stack-in-javascript

What is Call Stack in JavaScript

JavaScript Call Stack is a mechanism to keep track of multiple function calls and manage execution context. This article describes how the call stack works with examples.

event loop and callback queue

Event Loop and Callback Queue in JavaScript

The event loop keeps monitoring the call stack and callback queue for executing callback functions. Read more about web APIs, callback queue, microtask queue, event loops, and starvation.

Cannot read property of undefined in JavaScript

Cannot read property of undefined in JavaScript

The TypeError: Cannot read property of undefined occurs when we try to read a property on an undefined variable or when we try to access a property on a DOM element that doesn't exist.

Can't set headers after they are sent to the client

Can't set headers after they are sent to the client

Error “Can't set headers after they are sent to the client” occurs when an express.js application tries to send multiple responses for a single request.

Greatest Common Divisor (GCD) in JavaScript

Find greatest common divisor (GCD) in JavaScript

Find the Greatest Common Divisor(GCD) of two numbers using the Euclidean algorithm in javascript. Calculate GCD for a given integer array.

How to Fix error:0308010C:digital envelope routines::unsupported

How to Fix error:0308010C:digital envelope routines::unsupported

To fix the error:0308010C:digital envelope routines::unsupported, enable the legacy provider for Node.js by passing --openssl-legacy-provider flag to webpack.

Javascript

What are Parameters, Arguments and Arguments Object in JavaScript

In JavaScript, the terms parameters, arguments, and arguments object are related to functions. Explains what they are with examples.

ckeditor

How to Integrate Custom Build CKEditor5 with React

Explains how to create a custom build CKEditor5 and integrate with react with sample code.