Skip to content

Instantly share code, notes, and snippets.

@uran1980
Forked from dmnsgn/SingletonEnforcer.js
Created July 24, 2017 20:47
Show Gist options
  • Save uran1980/b1584e5769f555da0531e98a6de85c63 to your computer and use it in GitHub Desktop.
Save uran1980/b1584e5769f555da0531e98a6de85c63 to your computer and use it in GitHub Desktop.
ES6 singleton pattern: use Symbol to ensure singularity
// 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