DEV Community

Cover image for Singleton Design Pattern - Javascript
Tushar Koshti
Tushar Koshti

Posted on • Edited on • Originally published at blog.theawesomeprogrammer.com

Singleton Design Pattern - Javascript

Singleton Design Pattern

  • Singleton design pattern is one of the creational design patterns.
  • Singleton design pattern describes how the object should be created.
  • It ensures that the class has only one instance and provides a global access point to that instance.
  • Singleton design pattern is discovered because of bugs due to multiple instances where only one instance should be present.

When to use Singleton Design Pattern

  • We need to ensure only one instance of the class is present.
  • We need to provide a global access point to a class instance.

Code example

  • A logger is one of the real-world use cases in which we want to have a single instance globally.
let instance = null;

class Logger {
    constructor(logger_name) {
        if (!instance) {
            this.name = logger_name;
            instance = this;
        } else {
            return instance;
        }
    }
}

const logger_1 = new Logger('Logger1');
const logger_2 = new Logger('Logger2');

console.log(logger_1); // Logger {name: 'Logger1'}
console.log(logger_2); // Logger {name: 'Logger1'}

  • In this example, you can see that even if we try to create 2 different instances of the Logger class there will be only one instance of the Logger class.
  • You can find the code in the GitHub repository .

One Last Thing...

  • If you'd like to stay in the loop of Software Development then please subscribe to my newsletter. I will try my best to keep you informed about the latest trends and best practices for Software Development.

  • Please like and follow the blog post. Connect with me on Twitter and LinkedIn.

Let me know in the comments what you will like to learn next... Thanks for visiting the blog...

Top comments (0)