Created
August 20, 2016 22:06
-
-
Save ondratra/2909328eb2c28c2674d3c3b6ccf5e4d2 to your computer and use it in GitHub Desktop.
ECMA6 Singleton class
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
const constructorLock = Symbol(); | |
const singletonInstance = Symbol(); | |
export default class Singleton { | |
// constructor lock prevents class from being instantiate via 'new Singleton()' | |
// because constructorLock exists only in this file | |
constructor(lock) { | |
if (lock !== constructorLock) { | |
throw new Error('Cannot instantiate singleton directly. Use getter "instance".'); | |
} | |
} | |
static get instance() { | |
if (!this[singletonInstance]) { | |
this[singletonInstance] = new Singleton(constructorLock); | |
} | |
return this[singletonInstance]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment