Skip to content

Instantly share code, notes, and snippets.

@uyu423
Created January 3, 2018 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uyu423/2df5d94c9166bc04eb88d91e848df50e to your computer and use it in GitHub Desktop.
Save uyu423/2df5d94c9166bc04eb88d91e848df50e to your computer and use it in GitHub Desktop.
Common Node.js Singleton pattern
// Singleton.js
class Singleton {
constructor(initValue = 0) {
this.value = initValue;
}
setValue(value) {
this.value += value;
}
getValue() {
return this.value;
}
}
Singleton.instance = null
Singleton.getInstance = () => {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
module.exports = Singleton.getInstance();
// index.js
const Singleton = require('./Singleton');
const instA = Singleton;
const instB = Singleton;
instA.setValue(100);
console.log(instB.getValue()); // return 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment