Last active
March 19, 2018 14:45
-
-
Save KhalilZaidoun/e12da926f5f4c0033c8016af922788d2 to your computer and use it in GitHub Desktop.
Singleton ES6 pattern using Symbol to ensure singularity
This file contains hidden or 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
// https://stackoverflow.com/a/26227662 | |
const singleton = Symbol(); | |
const singletonEnforcer = Symbol() | |
class SingletonClass { | |
constructor(enforcer) { | |
if(enforcer != singletonEnforcer) throw "Cannot construct singleton"; | |
} | |
static get instance() { | |
if(!this[singleton]) { | |
this[singleton] = new SingletonClass(singletonEnforcer); | |
} | |
return this[singleton]; | |
} | |
} | |
export default SingletonClass; | |
// const instance = SingletonClass.instance; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment