lion/packages/core/src/LionSingleton.js
Thomas Allmer ec8da8f12c feat: release inital public lion version
Co-authored-by: Mikhail Bashkirov <mikhail.bashkirov@ing.com>
Co-authored-by: Thijs Louisse <thijs.louisse@ing.com>
Co-authored-by: Joren Broekema <joren.broekema@ing.com>
Co-authored-by: Gerjan van Geest <gerjan.van.geest@ing.com>
Co-authored-by: Erik Kroes <erik.kroes@ing.com>
Co-authored-by: Lars den Bakker <lars.den.bakker@ing.com>
2019-04-26 10:37:57 +02:00

50 lines
1.2 KiB
JavaScript

/* eslint-disable no-underscore-dangle */
/**
* 'LionSingleton' provides an instance of the given class via .getInstance(foo, bar) and will
* return the same instance if already created. It can reset its instance so a new one will be
* created via .resetInstance() and can at any time add mixins via .addInstanceMixin().
* It can provide new instances (with applied Mixins) via .getNewInstance().
*/
export class LionSingleton {
/**
* @param {function()} mixin
*/
static addInstanceMixin(mixin) {
if (!this.__instanceMixins) {
this.__instanceMixins = [];
}
this.__instanceMixins.push(mixin);
}
/**
* @param {...*} args
* @returns {LionSingleton}
*/
static getNewInstance(...args) {
let Klass = this;
if (Array.isArray(this.__instanceMixins)) {
this.__instanceMixins.forEach(mixin => {
Klass = mixin(Klass);
});
}
return new Klass(...args);
}
/**
* @param {...*} args
* @returns {*}
*/
static getInstance(...args) {
if (this.__instance) {
return this.__instance;
}
this.__instance = this.getNewInstance(...args);
return this.__instance;
}
static resetInstance() {
this.__instance = undefined;
}
}