Singleton Design Pattern - Javascript

Subscribe to my newsletter and never miss my upcoming articles

Singleton Design Pattern

What is 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.
  • This is how we can use singleton in javascript.

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...

Maxi Contieri's photo

Great Article

I wish you consider Singleton drawbacks

codeburst.io/singleton-the-root-of-all-evil..

Burhanuddin Udaipurwala's photo

Great article!

Tushar Koshti's photo

Thank you, Burhanuddin!!!