Sometimes the creation of an object can be complicated and the factory pattern can be used to simplify that and hide a lot of that from our front end. Basically, the factory pattern can help us simplify object creation and create different objects based on need. in this article, we will see simple examples to understand the factory pattern in JavaScript and the advantages over the others.
Let’s see the simplest way to creat an object by using object literal:
const person1 = {
name: 'Jhon',
sayHi: function() {
console.log('Hi');
}
}
const person2 = {
name: 'Sam',
sayHi: function() {
console.log('Hi');
}
}
In the above code, there is code duplication. the method sits in each object and it means that if there is a bug in this method, we will have to fix it in each object.
When we have one or more methods in an object it means that the object has behavior and creating an object that has a behavior with the object literal is not a good choice. We can use a constructor function or a factory to create an object that has a behavior.
Let’s see how we can change the above code with a factory function:
function createPerson(name) {
return {
name,
sayHi: function() {
console.log('Hi');
}
};
}
const person1 = createPerson('Jhon');
const person2 = createPerson('Sam');
console.log(person2.sayHi()); // Hi
console.log(person2.sayHi()); // Hi
As you can see above, the factory is basically a function that creates an object and returns it.
The factory is much simpler than a class and in most cases, you can use it to create an object instead of using a class. let’s see an example of a class versus a factory:
class Person {
constructor() {
this.greet = 'Howdy';
}
sayGreet() {
console.log(this.greet);
}
}
const person1 = new Person();
person1.sayGreet(); // Howdy
In the above code, we created a class and instantiate an object.
const person = () => {
const greet = 'Howdy';
return {
sayGreet: () => console.log(greet);
}
}
const person1 = person();
person1.sayGreet(); // Howdy
In the last example, we can see that the creation of the object is much simpler. we didn’t use the “this” and “new” keywords and we created a private property (greet) with the help of closures.