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());