avatarMahesh Kumawat

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5448

Abstract

e main entry point for our application.</p> <figure id="fb4f"> <div> <div>

            <iframe class="gist-iframe" src="/gist/maheshkumawat23/7313c5fd69598f485f052e64bf25b835.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="e81c">Within our index_singleton.js, we are also using the Logger. On line one we import the class, and on line five we create our third instance of the Logger. Now, this file also uses the store and shopper classes and on line nine we create a new instance of a shopper and on line 11 we’ll create a new instance of a store.Now notice on line seven, we are sending messages to the Logger. So, on line seven we’re going to log the message starting app and on line 24 we’re also going to log the message finished config.</p><p id="4c79">Now down here on line 25 of this file we’re using console log just to dump some debugging information. So here we’ll see how many messages have been saved inside of our Logger instance and on line 27 we’ll actually log each of those messages by mapping the logs array.So, the Logger instance stores an array called logs. We’re going to map over each item in that array, and we’re going to log the message that’s saved there to the console. Let’s go ahead and go out to our console and run this application.</p><p id="bbdf">node index_singleton.js</p><div id="b584"><pre><span class="hljs-attribute">2018</span>-<span class="hljs-number">04</span>-<span class="hljs-number">30</span>T14:<span class="hljs-number">43</span>:<span class="hljs-number">58</span>.<span class="hljs-number">748</span>Z - Strarting app....

<span class="hljs-attribute">2018</span>-<span class="hljs-number">04</span>-<span class="hljs-number">30</span>T14:<span class="hljs-number">43</span>:<span class="hljs-number">58</span>.<span class="hljs-number">897</span>Z - Shopper: alex has <span class="hljs-number">500</span> money in their account <span class="hljs-attribute">2018</span>-<span class="hljs-number">04</span>-<span class="hljs-number">30</span>T14:<span class="hljs-number">43</span>:<span class="hljs-number">58</span>.<span class="hljs-number">900</span>Z - New Store: Jai Vinayak Collection has <span class="hljs-number">2</span> items in stock <span class="hljs-attribute">2018</span>-<span class="hljs-number">04</span>-<span class="hljs-number">30</span>T14:<span class="hljs-number">43</span>:<span class="hljs-number">58</span>.<span class="hljs-number">901</span>Z - finsihed config.... <span class="hljs-attribute">Total</span> log count: <span class="hljs-number">2</span> <span class="hljs-attribute">Strarting</span> app.... <span class="hljs-attribute">finsihed</span> config....</pre></div><p id="40e1">we will notice that we see four logs. So we see our main application, log, starting the app along with its timestamp. We see that a new shopper has been created, a new store has been created, and then our main application has also finished running the configuration. The problem is, is because we have three instances of the Logger, we’re only looking at the information for the main instance. So in our debugging information down here we see two logs total and those logs are only starting app and finished config. Now the reason is, is whenever we looking at the current Logger instance, we’re only looking at the instance that was created within our main application.</p><p id="d347">Not the instance that was created within the shopper and the store. When we have this type of a problem a singleton can really come in handy.</p><p id="efd5"><b>How to create Singleton Instance in Node.js?</b></p><p id="8ec7">In the last Section we took a look at how creating multiple instances of the logger class can cause problems within our application. In this section we’re going to go ahead and fix those problems by implementing a singleton. So logger.js file let’s go ahead and modify this file to 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.</p><p id="9ffd">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.</p><p id="83cd">So the next thing we’re going to do for a classical singleton is actually return that instance using 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.</p> <figure id="e9fa"> <div> <div>

            <iframe class="gist-iframe" src="/gist/maheshkumawat23/bc95b0bdd146e561a301b9daf0358c3e.js" allowfullscreen="" frameborder=

Options

"0" height="undefined" width="undefined"> </div> </div> </figure></iframe></div></div></figure><p id="2748">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.</p> <figure id="494a"> <div> <div>

            <iframe class="gist-iframe" src="/gist/maheshkumawat23/e436a131e1a3e447776715d93431ce82.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="7a08">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.</p>
    <figure id="e051">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/maheshkumawat23/83be8639831762fec47861d810b23782.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="aef1">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.</p>
    <figure id="44a1">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/maheshkumawat23/49fa88472fbd5618825919e1149917f6.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="a4ae">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.</p><p id="2a1d">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.</p><div id="9f5a"><pre><span class="hljs-attribute">2018</span>-<span class="hljs-number">04</span>-<span class="hljs-number">30</span>T15:<span class="hljs-number">50</span>:<span class="hljs-number">22</span>.<span class="hljs-number">942</span>Z - starting app...

<span class="hljs-attribute">2018</span>-<span class="hljs-number">04</span>-<span class="hljs-number">30</span>T15:<span class="hljs-number">50</span>:<span class="hljs-number">22</span>.<span class="hljs-number">966</span>Z - New Shopper: alex has <span class="hljs-number">500</span> in their account. <span class="hljs-attribute">2018</span>-<span class="hljs-number">04</span>-<span class="hljs-number">30</span>T15:<span class="hljs-number">50</span>:<span class="hljs-number">22</span>.<span class="hljs-number">967</span>Z - New Store: Steep and Deep Supplies has <span class="hljs-number">2</span> items in stock. <span class="hljs-attribute">2018</span>-<span class="hljs-number">04</span>-<span class="hljs-number">30</span>T15:<span class="hljs-number">50</span>:<span class="hljs-number">22</span>.<span class="hljs-number">967</span>Z - finished config... <span class="hljs-attribute">4</span> logs total <span class="hljs-attribute">starting</span> app... <span class="hljs-attribute">New</span> Shopper: alex has <span class="hljs-number">500</span> in their account. <span class="hljs-attribute">New</span> Store: Steep and Deep Supplies has <span class="hljs-number">2</span> items in stock. <span class="hljs-attribute">finished</span> config...</pre></div><p id="3c46">Can we fix Singleton probelm without creating a new Singleton class. Answer is yes.</p><p id="d88c">I’m going to come into my logger.js file and just implement the singleton an easier way by removing the class. Or the need to export a single class and now on line 19 where I export this module, I’m going to just go ahead and export a new instance of the logger. The idea here is that when we run this file, it will run once, create the new instance of the logger, and save it in the cache. That means that Node JS will automatically handle exporting the same instance of the logger to every other module that wants to consume it.</p> <figure id="341e"> <div> <div>

            <iframe class="gist-iframe" src="/gist/maheshkumawat23/7d90ed5ed2ea89ddd8d57616f0aab06c.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="69d3">So, let’s just go ahead and modify our store.js file and Shopper.js. We are going to get rid of line three where we create the instance of the logger here because we’re going to import it directly from our logger module.</p><p id="515c">So, we are importing the instance and then I am getting rid of the line where we created the new logger instance. So, I go ahead and save this and we should have the exact same results without the need to create an extra class. So, let’s go ahead and test this out.</p></article></body>

Node.js Design Patterns — Singleton pattern ( Series -1)

What are Design Patterns?

So what exactly are design patterns? Well, every day that we’re building software, we are usually presented with a lot of challenging problems, problems that we might have already solved. When presented with re-occurring problems, we are faced with a decision. Solve the problem again and again for each application where it occurs, or solve the problem once and for all with an improved solution, a pattern, a solution that you can use over and over again in any type of application where this problem occurs. If you find your solution works well by proving it in various applications and situations, and you feel like you can safely use your solution a million times over, it might be time to make it official.

Give your solution a name. Document your solution, evangelize it. Get other developers using your solution to solve the same problem when they face it. You will have just created a design pattern. Design patterns are reusable, reliable solutions to problems that we face every day in software development. Design patterns are named, cataloged solutions. They are well-tested and reusable in many different situations. They are well-documented so other developers can learn them, and they are easy to talk about with other engineers who already know them.

They make your code better and your applications less brittle. It’s easier to add new features or modules to applications where you use them. Although some design patterns may be difficult to learn at first, they ultimately simplify your code. Their aim is to present solutions for decoupling objects or modules and reducing the overall complexity of your architecture. Not only will understanding design patterns make you write better code, they will make you a better programmer, because learning design patterns gives you techniques that you can use when faced with common programming problems and a knowledge base that is easy to discuss at, say, an interview.

As a programmer who wants to write better code and reflect on better ways of doing things, learning and using design patterns is a must.

So in this series of node.js design pattern i am first going to put focus on Creation Design Pattern.

The Singleton Problem

Sometimes you need to make sure that you have one and only one instance of an object. This is where the singleton pattern can be useful. A singleton represents a single instance of an object. Only one can be created, no matter how many times the object is instantiated. If there’s already an instance, the singleton will create a new one. Let’s take a look at where creating multiple instances of one object might create problems within our application.

Lets create some files in node.js. First file is Logger.js.

Within this file, we create a class called Logger. The idea is that we want our application modules to use this logger class instead of using console log directly. This logger saves information about all of the logs that are sent to it and it also logs each message with a timestamp. So once we create an instance of this object we can use the log method, send it a message, and it will log the timestamp and the message to the terminal as well as save information about that log.

Created another file named as Store.js

Now if you look at this file we actually use the Logger. On line one, we import the Logger class, and on line three we create a new instance called Logger so that we can actually use this class. So on line 10, within the store constructor we will log a new message every time a store is created. So it says New Store and it gives us the name of the store and how many items are in stock.

The third file we have is Shopper.js

If you take a look at the shopper.js file it also uses the Logger, and on line 3 it creates its own instance of the Logger. So, whenever we create new shoppers on line 10 within the constructor, we will log a message to the console that says a new shopper has been created,this is their name and this is how much money they have in their account.

Finally, the index_singleton.js, the main entry point for our application.

Within our index_singleton.js, we are also using the Logger. On line one we import the class, and on line five we create our third instance of the Logger. Now, this file also uses the store and shopper classes and on line nine we create a new instance of a shopper and on line 11 we’ll create a new instance of a store.Now notice on line seven, we are sending messages to the Logger. So, on line seven we’re going to log the message starting app and on line 24 we’re also going to log the message finished config.

Now down here on line 25 of this file we’re using console log just to dump some debugging information. So here we’ll see how many messages have been saved inside of our Logger instance and on line 27 we’ll actually log each of those messages by mapping the logs array.So, the Logger instance stores an array called logs. We’re going to map over each item in that array, and we’re going to log the message that’s saved there to the console. Let’s go ahead and go out to our console and run this application.

node index_singleton.js

2018-04-30T14:43:58.748Z - Strarting app....
2018-04-30T14:43:58.897Z - Shopper: alex has 500 money in their account
2018-04-30T14:43:58.900Z - New Store: Jai Vinayak Collection has 2 items in stock
2018-04-30T14:43:58.901Z - finsihed config....
Total log count: 2
Strarting app....
finsihed config....

we will notice that we see four logs. So we see our main application, log, starting the app along with its timestamp. We see that a new shopper has been created, a new store has been created, and then our main application has also finished running the configuration. The problem is, is because we have three instances of the Logger, we’re only looking at the information for the main instance. So in our debugging information down here we see two logs total and those logs are only starting app and finished config. Now the reason is, is whenever we looking at the current Logger instance, we’re only looking at the instance that was created within our main application.

Not the instance that was created within the shopper and the store. When we have this type of a problem a singleton can really come in handy.

How to create Singleton Instance in Node.js?

In the last Section we took a look at how creating multiple instances of the logger class can cause problems within our application. In this section we’re going to go ahead and fix those problems by implementing a singleton. So logger.js file let’s go ahead and modify this file to 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 instance using 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.

2018-04-30T15:50:22.942Z - starting app...
2018-04-30T15:50:22.966Z - New Shopper: alex has 500 in their account.
2018-04-30T15:50:22.967Z - New Store: Steep and Deep Supplies has 2 items in stock.
2018-04-30T15:50:22.967Z - finished config...
4 logs total
   starting app...
   New Shopper: alex has 500 in their account.
   New Store: Steep and Deep Supplies has 2 items in stock.
   finished config...

Can we fix Singleton probelm without creating a new Singleton class. Answer is yes.

I’m going to come into my logger.js file and just implement the singleton an easier way by removing the class. Or the need to export a single class and now on line 19 where I export this module, I’m going to just go ahead and export a new instance of the logger. The idea here is that when we run this file, it will run once, create the new instance of the logger, and save it in the cache. That means that Node JS will automatically handle exporting the same instance of the logger to every other module that wants to consume it.

So, let’s just go ahead and modify our store.js file and Shopper.js. We are going to get rid of line three where we create the instance of the logger here because we’re going to import it directly from our logger module.

So, we are importing the instance and then I am getting rid of the line where we created the new logger instance. So, I go ahead and save this and we should have the exact same results without the need to create an extra class. So, let’s go ahead and test this out.

JavaScript
Nodejs
Design Patterns
Recommended from ReadMedium