Skip to content

Instantly share code, notes, and snippets.

@KhalilZaidoun
Last active March 19, 2018 14:45
Show Gist options
  • Save KhalilZaidoun/e12da926f5f4c0033c8016af922788d2 to your computer and use it in GitHub Desktop.
Save KhalilZaidoun/e12da926f5f4c0033c8016af922788d2 to your computer and use it in GitHub Desktop.
Singleton ES6 pattern using Symbol to ensure singularity
// 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