Skip to content

Instantly share code, notes, and snippets.

@dmnsgn
Created April 16, 2016 17:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dmnsgn/6abeb1ed9111edf2e0a30511f1f968b2 to your computer and use it in GitHub Desktop.
Save dmnsgn/6abeb1ed9111edf2e0a30511f1f968b2 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