Google trends Public Holidays Coupon Code Code Compiler

Implementing the Singleton Design Pattern in Nodejs


Sep 11, 2023

In Node.js, the Singleton pattern can be used to ensure that a class has only one instance, and that instance is shared across different parts of your application. This can be useful when you want to centralize access to a resource or configuration that should be shared among different modules or components.

Here's an example of how to implement the Singleton pattern in Node.js:


// Singleton.js

class Singleton {
  constructor() {
    if (!Singleton.instance) {
      // Create a new instance if it doesn't exist
      this.data = [];
      Singleton.instance = this;
    }

    return Singleton.instance;
  }

  // You can add methods and properties to the singleton instance
  addItem(item) {
    this.data.push(item);
  }

  getItems() {
    return this.data;
  }
}

// Export the Singleton instance
module.exports = new Singleton();

In this example, we create a Singleton class with a private instance property. When you create a new instance of the Singleton class, it checks whether an instance already exists. If an instance exists, it returns the existing instance; otherwise, it creates a new one.

Now you can use the Singleton in different parts of your Node.js application like this:


// ModuleA.js
 const singlet

singletonInstance.addItem('Item A from ModuleA');

// ModuleB.js
 const singlet

singletonInstance.addItem('Item B from ModuleB');

// Main.js
 const singlet

console.log(singletonInstance.getItems());

Copyright 2024. All rights are reserved