Skip to content

Instantly share code, notes, and snippets.

@CGavrila
Created August 22, 2015 19:11
Show Gist options
  • Save CGavrila/3499529123b8bec955f8 to your computer and use it in GitHub Desktop.
Save CGavrila/3499529123b8bec955f8 to your computer and use it in GitHub Desktop.
Singleton pattern in ECMAScript 6
let _singleton = Symbol();
class Singleton {
constructor(singletonToken) {
if (_singleton !== singletonToken)
throw new Error('Cannot instantiate directly.');
}
static get instance() {
if(!this[_singleton])
this[_singleton] = new Singleton(_singleton);
return this[_singleton]
}
}
export default Singleton;
Copy link

ghost commented Feb 24, 2016

Why singletonToken?

@jhm-ciberman
Copy link

@dpavlica Because in this way the singleton cannot be created with the new operator, unless you have access to the singleton symbol.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment