Improve documentation of Singleton functions, change to createInstance (#2585)

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton authored and GitHub committed 2021-04-22 10:05:29 +03:00
1 parent 33ca6c9c17
commit b63fdfaff3
15 files changed
+90 -68

No files matched your search

+32 -9
View File
@@ -1,10 +1,3 @@
/**
* Narrowing class instances to the one.
* Use "private" or "protected" modifier for constructor (when overriding) to disallow "new" usage.
*
* @example
* const usersStore: UsersStore = UsersStore.getInstance();
*/
type StaticThis<T, R extends any[]> = { new(...args: R): T };
export class Singleton {
@@ -13,12 +6,28 @@ export class Singleton {
constructor() {
if (Singleton.creating.length === 0) {
throw new TypeError("A singleton class must be created by getInstanceOrCreate()");
throw new TypeError("A singleton class must be created by createInstance()");
}
}
static getInstanceOrCreate<T, R extends any[]>(this: StaticThis<T, R>, ...args: R): T {
/**
* Creates the single instance of the child class if one was not already created.
*
* Multiple calls will return the same instance.
* Essentially throwing away the arguments to the subsequent calls.
*
* Note: this is a racy function, if two (or more) calls are racing to call this function
* only the first's arguments will be used.
* @param this Implicit argument that is the child class type
* @param args The constructor arguments for the child class
* @returns An instance of the child class
*/
static createInstance<T, R extends any[]>(this: StaticThis<T, R>, ...args: R): T {
if (!Singleton.instances.has(this)) {
if (Singleton.creating.length > 0) {
throw new TypeError("Cannot create a second singleton while creating a first");
}
Singleton.creating = this.name;
Singleton.instances.set(this, new this(...args));
Singleton.creating = "";
@@ -27,6 +36,13 @@ export class Singleton {
return Singleton.instances.get(this) as T;
}
/**
* Get the instance of the child class that was previously created.
* @param this Implicit argument that is the child class type
* @param strict If false will return `undefined` instead of throwing when an instance doesn't exist.
* Default: `true`
* @returns An instance of the child class
*/
static getInstance<T, R extends any[]>(this: StaticThis<T, R>, strict = true): T | undefined {
if (!Singleton.instances.has(this) && strict) {
throw new TypeError(`instance of ${this.name} is not created`);
@@ -35,6 +51,13 @@ export class Singleton {
return Singleton.instances.get(this) as (T | undefined);
}
/**
* Delete the instance of the child class.
*
* Note: this doesn't prevent callers of `getInstance` from storing the result in a global.
*
* There is *no* way in JS or TS to prevent globals like that.
*/
static resetInstance() {
Singleton.instances.delete(this);
}