Factory Design Pattern In JavaScript

In this article, we will learn about Factory Pattern, one of the core design principles in JavaScript.

We all know that a factory creates an object or product and sells it to the consumer. Let’s take an example of a Video game. We all play on PS4 but most consumers are not aware of how PS4 was made. They just buy the product and start using it.
 
Factory Design pattern is the same idea. It is a part of the Creational Design Pattern.
 
The basic concept of the Factory Pattern is to create an object that, in turn, create other objects based on conditions.
 

When Do We Need a Factory Pattern?

 
We need to choose Factory Pattern under the following circumstances:
  • The Classes don’t know what exact sub-classes they have to create
  • The Object needs to be extended to subclasses
  • The Product implementation tends to change over time and the Client remains unchanged
Let’s take an example,
 
In this example, we are creating a function which will return an instance of a class based on a certain condition.
  1. let Factory = () => {  
  2.     let data;  
  3.     this.getType = (type) => {  
  4.         if (type === 'one') {  
  5.             data = require('./class-one')();  
  6.         }  
  7.         if (type === 'two') {  
  8.             data = require('./class-two')();  
  9.         }  
  10.         return data;  
  11.     }  
  12. }  
  13. Factory.getType('two');  
Factory Pattern allows the following,
  1. To separate the object creation from its implementation
  2. To create different instances based on conditions
  3. Not to expose the constructor of the class/objects.
Now, let’s take a real-world implementation to understand about Factory Pattern.
 
Factory Design Pattern In JavaScript

UML diagram for the example

 
As discussed earlier, the Client (the gamer) will make a deal with the store (User Factory) to use the service. The Factory will create the PS4 (internal implementation) which will be hidden from the outside world.
 
person.js 
  1. class Person {      
  2.     constructor(name){      
  3.         this.name = name;      
  4.     }      
  5. }      
  6.       
  7. module.exports = Person;   
We have created a parent class Person which contains the common property (ex: name) for student and instructor. We can also add another class, like employee, sportsman, etc.
 
student.js 
  1. const Person = require('./person');  
  2. class Student extends Person {  
  3.     constructor(name, level) {  
  4.         super(name);  
  5.         this.level = level;  
  6.     }  
  7.     toString() {  
  8.         return JSON.stringify(this);  
  9.     }  
  10. }  
  11. module.exports = Student;  
instructor.js
  1. const Person = require('./person');  
  2. class Instructor extends Person {  
  3.     constructor(name, position, earnings) {  
  4.         super(name);  
  5.         this.position = position;  
  6.         this.earnings = earnings;  
  7.     }  
  8.     toString() {  
  9.         return JSON.stringify(this);  
  10.     }  
  11. }  
  12. module.exports = Instructor;  
We have created two child classes which were inherited from parent class (person.js), with their own certain properties. The toString() method will print the current instance of the specified class.
 
userFactory.js
  1. const Instructor = require('./instructor');  
  2. const Student = require('./student');  
  3. const userFactory = (type, name, position, earnings = 0, level = 'Beginner') => {  
  4.     if (type === 'instructor') {  
  5.         return new Instructor(type, name, position, earnings);  
  6.     }  
  7.     if (type === 'student') {  
  8.         return new Student(type, name, level);  
  9.     }  
  10. }  
  11. module.exports = userFactory;  
In this file, we are creating a factory which will create the instance based on client requirements. As we know creating instance will take up some memory space, hence it’s a good practice to create an instance which we need for a specified purpose.
 
main.js
  1. const userFactory = require('./userFactory');        
  2. const paul = userFactory('instructor''Paul''software engineer', 1000);      
  3. const john = userFactory('student''John''Beginner');      
  4. console.log(paul.toString());      
  5. console.log(john.toString());   
From the main.js file we are calling the factory method ‘userFactory’ and passing our requirements. Hence we are getting instance of our specific needs.
 
In this blog, you have learned about the factory pattern design principle in JS. Hope you have liked it. In my next article, you will come across the other design patterns, such as Singleton, Builder Pattern, etc. in JavaScript.