Design Pattern (Singleton) + NodeJs — Parte 1

Renan Deocleciano
2 min readApr 11, 2021

This article is part of my channel on Youtube. So, if you like share with your friends.

SINGLETON — What the hell is Singleton?

Singletons, are objects that have only a single instance and a single access point.
NodeJs provides a basic module system for implementing a singleton.
These modules are cached when they need to be accessed using a require(). Let’s see below:

Are we going to bring this module into a real understanding scenario?
First of all, we will create two files. One called calculator.js and the other app.js

Calculator.js

App.js

Now, run app.js and see the behavior.

This behavior happens because, as we already said, these modules are cached by Node.
What if we are going to work with class? How would we do it?
To exemplify, let’s imagine the following scenario:
A simple shopping cart that will be associated with a particular user.

So, let’s create four files:

  • App.js
  • Cart.js
  • User.js
  • Shop.js

When I think of a solution to any problem, I like to start from the end to begin. In this case Shop until App.

Shop.js

Now let’s create our User.js

Let’s create the Cart.js

And now to finish, let’s go to the App.js

Now are we going to run the application?

  • > node app.js

If you created files with the same code, you will see that something is wrong. Right?

This is because when working with classes, we must instantiate the class before exporting it. In doing so we will working with a Singleton Design Pattern.

Shall we fix our code?

Shopp.js

User.js

Cart.js

Now we are using a Singleton! Let’s run app.js again and check the result.

In the next article I will cover the Factory pattern!

Thanks to you who read this far!!!

--

--