Design Pattern in JavaScript

Mragang Jain
Airtel Digital
Published in
4 min readJun 29, 2023

Introduction

At Airtel, we continuously emphasise on the importance of design patterns and their role in writing efficient and robust software. Incorporating design patterns into our development process allows us to deliver high-quality solutions that meet our customers’ diverse needs.

In the dynamic world of software development, design patterns serve as valuable tools for creating scalable, maintainable, and efficient code. Among these patterns, the Singleton design pattern stands out for its ability to guarantee the existence of only one instance of a class and offer a unified access point throughout the application. At Airtel, we recognise the significance of design patterns in our software development process, and in this blog post, we will delve into the Singleton design pattern, providing a detailed explanation and a practical implementation using JavaScript.

Understanding the Singleton design pattern

The Singleton design pattern is a creational design pattern that restricts the instantiation of a class to a single object. It guarantees that there is only one instance of the class throughout the application and provides a global access point to that instance. Singleton design pattern guarantees that only one instance of a particular class exists, and it provides a mechanism to access that instance globally. This can be useful in situations where having multiple instances of a class would create issues or unnecessary resource consumption.

Here is an example of how to use a Singleton design pattern in JavaScript:

const Singleton = (() => {
let instance;

function createInstance() {
// Private members and methods
// ...

return {
// Public members and methods
// ...
};
}

return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();

// Usage:
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

console.log(instance1 === instance2); // true

By invoking Singleton.getInstance(), we obtain the Singleton instance. Multiple invocations of getInstance() will always return the same instance. Let’s see some complex example now.

class Logger {
constructor() {
if (Logger.instance === null) {
this.log = []
Logger.instance = this // Create New instance
}
return Logger.instance // Return same instance
}
log(message) {
this.log.push(message)
}
printLogCount() {
console.log(`${this.logs.length} Logs`)
}
}

const logger = new Logger()
// It just freeze the Object so that another function or variible can't be added
Object.freeze()
export default logger

Here is the Logger Class which return the single instance.

import logger from "./logger.js"

export default function Component1(){
logger.printLogCount()
logger.log("Frist Component")
logger.printLogCount()
}
import logger from "./logger.js"

export default function Component2(){
logger.printLogCount()
logger.log("Second Component")
logger.printLogCount()
}

Advantage of using Singleton design pattern in this example is when you try to log the count of logger it will print the entire logs of all components. But if you try to create new instance it will print the particulars component logs.

In Airtel, we have harnessed the power of the Singleton design pattern to implement both backend and frontend components effectively. By leveraging this pattern, we guarantee the existence of a single instance of critical classes, including data controllers, data processors, and user interfaces. This approach enables us to establish centralised access and management of data across various tools, fostering consistency and optimising resource utilisation. With the Singleton design pattern in place, communication and coordination between backend and frontend components within our data mesh tool have been streamlined, leading to enhanced efficiency and performance.

Conclusion: The Singleton design pattern is a powerful tool for managing a single instance of a class in JavaScript. It ensures that there is only one instance throughout the application and provides a global access point to that instance. By using closures and a static method, we can easily implement the Singleton design pattern in JavaScript. Remember to use the Singleton design pattern judiciously, as it can introduce global state, which may impact testability and code maintainability.

By implementing the Singleton design pattern in JavaScript, our development team ensures that critical classes have only one instance throughout the application, reducing memory overhead and preventing potential conflicts. Singleton design pattern not only facilitates centralised access but also promotes code reusability and maintainability.

Thanks for reading!

We hope this blog post has shed light on the Singleton design pattern and its application in JavaScript. Incorporating this pattern in your projects can undoubtedly elevate your code’s performance and organisation, making it easier to scale and maintain in the long run.

For More Design Pattern Blogs Don’t forget to subscribe ⭐️

--

--

Mragang Jain
Airtel Digital

A frontend developer who love designing web applications.