-
-
Save geminiyellow/438b58b0ad02b9735d2e to your computer and use it in GitHub Desktop.
ES6 Singleton example. Use: import Singleton from 'Singleton'; let instance = Singleton.instance;
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
'use strict'; | |
/** | |
* Created by Alexander Litvinov | |
* Email: [email protected] | |
* May be freely distributed under the MIT license | |
*/ | |
let singleton = Symbol(); | |
let singletonEnforcer = Symbol(); | |
class Singleton { | |
/** | |
* @param enforcer | |
*/ | |
constructor(enforcer) { | |
if (enforcer !== singletonEnforcer) { | |
throw "Cannot construct singleton" | |
} | |
} | |
/** | |
* @returns Singleton | |
*/ | |
static get instance() { | |
if (!this[singleton]) { | |
this[singleton] = new Singleton(singletonEnforcer); | |
} | |
return this[singleton]; | |
} | |
} | |
export default Singleton; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment