How to implement simple Factory Pattern in Node.js


Instead of using class constructors or new keyword to create an object of a class, we can abstract this process. So, we can determine the type of object at run-time, by the time of generating that class object. The implementation seems like Factory Method, but simpler than Factory Method. This simple Factory is not treated as a standard GoF design pattern, but the approach is common to any place where we want to separate the code that varies a lot from the code that does not vary.

In this tutorial, grokonez shows you how to do it in NodeJs.

Nodejs simple Factory Pattern example


In this example, we have 3 types of cars: Audi, BMW, Mercedes. The car generating process depends on the input string "Audi" or "BMW" or "Mercedes".

CarFactory is the Factory class. In the client, we won’t use new keyword but create() method to create a new car:

Sample Structure


Implement simple Factory Pattern in Nodejs

Create default class

This Car class is a parent class for Audi, BMW, Mercedes class that we’re gonna create in the next steps.


This class has constructor method that assign a generated id to the car’s name and a showInfo() method to show the name field.

Create subclasses of default class

Now we create 3 classes: Audi, BMW, Mercedes that extends default Car class above.




Create Factory class

The CarFactory class has create() method that genetes new car based on the input string type.


Use simple Factory in Client


Check the result

Run the code with command: node app.js. Here is the result:

Some notes

– Why don’t we create the objects using new keyword?
Because we want to separate the part of code that is most likely to change from the others. In the future, if we need to modify the process of creating objects, we only need to change code inside the create() method of SimpleFactory class. So this client is not affected by these modifications.

– Cons of using simple factory method:
In case we want to add a new Car subclass, or delete an existing one, we have to change code in the factory’s create() method.


We’ve learned how to use simple factory method to create objects in a cleaner and resilient way that gives us an easy-to-understand interface of our package’s function. This pattern is extremely useful when writing NPM package for public use.

By grokonez | April 2, 2019.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *