-
-
Save uran1980/b1584e5769f555da0531e98a6de85c63 to your computer and use it in GitHub Desktop.
ES6 singleton pattern: use Symbol to ensure singularity
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
// http://stackoverflow.com/a/26227662/1527470 | |
const singleton = Symbol(); | |
const singletonEnforcer = Symbol(); | |
class SingletonEnforcer { | |
constructor(enforcer) { | |
if (enforcer !== singletonEnforcer) { | |
throw new Error('Cannot construct singleton'); | |
} | |
this._type = 'SingletonEnforcer'; | |
} | |
static get instance() { | |
if (!this[singleton]) { | |
this[singleton] = new SingletonEnforcer(singletonEnforcer); | |
} | |
return this[singleton]; | |
} | |
singletonMethod() { | |
return 'singletonMethod'; | |
} | |
static staticMethod() { | |
return 'staticMethod'; | |
} | |
get type() { | |
return this._type; | |
} | |
set type(value) { | |
this._type = value; | |
} | |
} | |
export default SingletonEnforcer; | |
// ... | |
// index.js | |
import SingletonEnforcer from './SingletonEnforcer'; | |
// Instantiate | |
// console.log(new SingletonEnforcer); // Cannot construct singleton | |
// Instance | |
const instance3 = SingletonEnforcer.instance; | |
// Prototype Method | |
console.log(instance3.type, instance3.singletonMethod()); | |
// Getter/Setter | |
instance3.type = 'type updated'; | |
console.log(instance3.type); | |
// Static method | |
console.log(SingletonEnforcer.staticMethod()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment