Utility
Gestion des Singletons
SingletonManager
est une classe utilitaire qui permet d'enregistrer, de récupérer et de désenregistrer des singletons.
Enregistrement, Récupération et Désenregistrement (sans arguments)
import { SingletonManager } from '@basalt-lab/basalt-helper/util';
// Example class with a static counter allow to see the number of instances created of this class
class Example {
private static _count = 0;
private readonly _id: number;
public constructor() {
Example._count += 1;
this._id = Example._count;
console.log(`Example created with ID: ${this._id}`);
}
public sayHello(): void {
console.log(`Hello from instance ${this._id}!`);
}
}
// allows to register the class Example as a singleton
SingletonManager.register('Example', Example);
// Get the singleton instance of Example
SingletonManager.get<Example>('Example').sayHello();
SingletonManager.get<Example>('Example').sayHello();
// allows to unregister the class Example as a singleton
SingletonManager.unregister('Example');
node example.jsExampleSingleton created with ID: 1
Hello from instance 1!
Hello from instance 1!
Hello from instance 1!
Hello from instance 1!
Enregistrement, Récupération et Désenregistrement (avec des arguments)
import { SingletonManager } from '@basalt-lab/basalt-helper/util';
// Example class with a static counter allow to see the number of instances created of this class
class Example {
private static _count = 0;
private readonly _id: number;
public constructor(name: string) {
Example._count += 1;
this._id = Example._count;
console.log(`Example created with ID: ${this._id} and name: ${name}`);
}
public sayHello(): void {
console.log(`Hello from instance ${this._id}!`);
}
}
// allows to register the class Example as a singleton
SingletonManager.register('Example', Example, 'John Doe');
// Get the singleton instance of Example
SingletonManager.get<Example>('Example').sayHello();
SingletonManager.get<Example>('Example').sayHello();
// allows to unregister the class Example as a singleton
SingletonManager.unregister('Example');
node example.jsExampleSingleton created with ID: 1 and name: John Doe
Hello from instance 1!
Hello from instance 1!
Hello from instance 1!
Hello from instance 1!