Factory Design Pattern in Javascript, What Does Do?

Design patterns in software development are awesome. Because design patterns solves many problems most of the time. So i think learning design patterns in software development is a must. And Factory Design Pattern is one of the most popular one.

Let’s start with an example. A classical example for prototypical inheritence.

const Person = function(name) { this.name = name; }

Person.prototype.eat = function() { console.log(this.name + " eats”); }

Now we can use Person and its methods.

const desmond = new Person("desmond"); const john = new Person("john");

desmond.eat(); // Logs "desmond eats" john.eat(); // Logs "john eats"

Here there are some problems if you are developing an enterprise application and if “Person” is one the most used methods of your app. Because everytime you use “Person” you must use new keyword. And if you forget to use new keyword interpreter doesn’t complain and bug finding becomes very difficult.

So here factory pattern comes as solution.

const Person = function(name){ const person = {}; person.name = name; person.eat = function(){ console.log(this.name + " eats"); } return person; };

and now we can do this.

const desmond = Person("desmond"); const john = Person("john");

desmond.eat(); // Logs "desmond eats" john.eat(); // Logs "john eats"

This is a short and quick example for “Factory Design Pattern”.