Created
August 22, 2015 19:11
-
-
Save CGavrila/3499529123b8bec955f8 to your computer and use it in GitHub Desktop.
Singleton pattern in ECMAScript 6
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
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@dpavlica Because in this way the singleton cannot be created with the new operator, unless you have access to the singleton symbol.