Tuesday, March 19, 2024

Implementing the Singleton Design Pattern in JavaScript

When working in applications, it is imperative that you design solutions that are maintainable and the code is readable. You should be able to find out the recurring problems in designs and then adopt a strategy to mitigate them. This way, you can write much clean, better and maintainable code. This is exactly where design patterns come to play.

Design patterns provide solutions to problems that occur often in software engineering. Such solutions are proven and time-tested. The Singleton design pattern is a Gang of Four (GOF) design pattern. It falls under the “creational design pattern” category. Creational design patterns are those that deal with object creation. There are two other categories of GOF design patterns, namely, structural patterns and behavioral patterns.

In this series of articles, we will implement the GOF design patterns using JavaScript. Incidentally, JavaScript is a dynamic, weakly-typed scripting language that provides support for many of the OOP features. This article, the first part in this series of articles on design patterns, presents a discussion on how we can implement the Singleton design pattern using JavaScript.

What is the Singleton design pattern?

The Singleton design pattern is a creational pattern that states that one and only one instance of a class would persist in the memory during the application’s life cycle. In other words, this design pattern restricts instantiation of a class to just one object. As far as JavaScript is concerned, a singleton is an instance that is created just once — any repeated calls to the constructor would always fetch the same instance.

Implementing the Singleton pattern

An easy way to implement the Singleton design pattern in JavaScript is by using an object literal as shown below.

var singleton = {
  method1: function () {
    //Write your usual code here
     },
     method2: function () {
     //Write your usual code here 
     }
};

Here’s is another code snippet that illustrates how you can implement the Singleton pattern in JavaScript.

var Singleton = (function(){
    function Singleton() {
        //Write your usual code here
    }
    var instance;
    return {
        getInstance: function(){
            if (null == instance) {
                instance = new Singleton();               
                instance.constructor = null; // Note how the constructor is hidden to prevent instantiation
            }
            return instance; //return the singleton instance
        }
   };
})();

Refer to the code snippet given above. Note how a check is made to see if the instance is null. If the instance is null, a new instance is created and returned by suppressing/hiding the constructor. If the instance is non-null, the instance is returned. This approach is also known as the module pattern. As you can see, you can encapsulate the private members that belong to a particular instance using closures.

Now that we have implemented our Singleton class, the following code snippet can be used to invoke the function.

var justOneInstance = Singleton.getInstance();

The GOF states: “The Singleton Pattern limits the number of instances of a particular object to just one. This single instance is called the singleton. Singletons are useful in situations where system-wide actions need to be coordinated from a single central place. An example is a database connection pool. The pool manages the creation, destruction, and lifetime of all database connections for the entire application ensuring that no connections are ‘lost’.”

Summary This article presented a discussion on the Singleton design pattern, why it is useful and how it can be implemented in JavaScript with code examples wherever appropriate. In future articles in this series, we will explore the other design patterns and examine how they can be implemented in JavaScript. Happy reading!

Reference

JavaScript Patterns: Build Better Applications with Coding and Design Patterns – by Stoyan Stefanov

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured