Created
January 3, 2018 20:17
-
-
Save uyu423/2df5d94c9166bc04eb88d91e848df50e to your computer and use it in GitHub Desktop.
Common Node.js Singleton pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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