Web Development, Node.js

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. If you go to your exercise files for chapter two, lesson one, within the Start folderyou will notice that there is a logger.js file.
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. We also have a store.js file. Now if you look at this file we actually use the Logger.

Leave a Comment