Node js Design Pattern, The Singletons pattern

In the last lesson we took a look at how creating multiple instances of the logger class can cause problems within our application. In this lesson we’re going to go ahead and fix those problems by implementing a singleton.

So within your exercise files, under chapter two lesson two within the start folder and the logger.js file let’s go ahead and modify this fileto export a singleton instead of a logger. So on line 17 I’m just going to come in here and add a new class called singleton. So this class is only going to allow us to create one instance of the logger. Anytime we need that instance we’re going to retrieve it through a get instance method.

So let’s go ahead and add a constructor to our singleton class. And what we want to do within this constructor is we want to check and see if an instance has already been created. So I’m going to save the instance directly to the class. So if there’s not a singleton instance then we want to create one. So if we don’t have one then the singleton instance will equal new logger.So that’s our singleton. And it will only allow us to create one instance whenever we instantiate this singleton class.

So the next thing we’re going to do for a classical singleton is actually return that instanceusing a get instance method. And what we can do within this method is return our singleton.instance. There we go. So this class only allows us to instantiate one logger and then using the get instance method we can return that logger to any file that wants to use it.So let’s go ahead and go into our store. We need to modify line three, where we create a new instance of our logger class to have a .getInstance chained on that call.

So this will return our single instance. And then within the shopper js we need to do the same thing also on line three .getInstance. And now both the store and the shopper should be using the same single instance of the logger. Within the index.js file we’ll also chain on a .getInstance and now all three of these files should be using the exact same instance of the logger. So we can check this by going to run our application. So let’s go out to the terminal and node index.js. And now we see the same output. We see four logs starting the app coming from our index file.

New shopper coming from the shopper file. New store coming from the store file. And then finished config coming from the index. And we also see the correct amount of logs within our logger instance. So it says that we have four logs total and it shows us that all four of these logs have made it even though we’re using the logger throughout multiple files.

Leave a Reply

avatar
1000
  Subscribe  
Notify of