From the course: Node.js: Design Patterns

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

The Singletons pattern

The Singletons pattern - Node.js Tutorial

From the course: Node.js: Design Patterns

Start my 1-month free trial

The Singletons pattern

- [Instructor] 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 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…

Contents