Skip to content

Instantly share code, notes, and snippets.

@YozhEzhi
Forked from dmnsgn/SingletonEnforcer.js
Last active February 25, 2017 14:53
Show Gist options
  • Save YozhEzhi/3d4d12c2e6cd38427e1eefda94517c6b to your computer and use it in GitHub Desktop.
Save YozhEzhi/3d4d12c2e6cd38427e1eefda94517c6b to your computer and use it in GitHub Desktop.
ES6 singleton pattern: constructor returns an instance scoped to the module. Without using the `new` operator.
const singleton = Symbol();
const singletonEnforcer = Symbol();
class Singleton {
constructor(enforcer) {
if (enforcer !== singletonEnforcer) {
throw new Error('Cannot construct singleton');
}
this._type = 'Singleton';
}
static get instance() {
if (!this[singleton]) {
this[singleton] = new Singleton(singletonEnforcer);
}
return this[singleton];
}
singletonMethod() {
return 'singletonMethod';
}
static staticMethod() {
return 'staticMethod';
}
get type() {
return this._type;
}
set type(value) {
this._type = value;
}
}
export default Singleton;
// index.js
import Singleton from './Singleton';
// Instantiate
// console.log(new Singleton); // => Cannot construct singleton
// Instance
const instance2 = Singleton.instance;
// Prototype Method
console.log(instance2.type, instance2.singletonMethod());
// Getter/Setter
instance2.type = 'type updated';
console.log(instance2.type);
// Static method
console.log(Singleton.staticMethod());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment