The Singleton Pattern is a creational design pattern that ensures a class has
only one instance while providing a global point of access to it. This pattern
is commonly used to manage shared resources or enforce a single point of
control
in an application.
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
classSingleton{publicstaticgetInstance<TextendsSingleton>(this:new()=>T):T{// Generic to handle subclasses
Singleton._instance||=newthis();returnSingleton._instanceasT;}privatestatic_instance: Singleton|undefined=undefined;// Private static instance
protectedconstructor(){// Protected constructor to prevent direct instantiation
// Any initialization logic here
}}classExampleClassextendsSingleton{privateproperties: Record<string,any>={};// Proper type for properties
constructor(){super();}set(key: string,value: any):void{// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.properties[key]=value;}get(key: string):any{returnthis.properties[key];}}constexample={run():void{constexample=ExampleClass.getInstance();// Type-safe instantiation
example.set("Singleton","This is a singleton value");console.log(example.get("Singleton"));constexample2=ExampleClass.getInstance();// Will return the same instance
if(example===example2){console.log("Both variables point to the same instance");}}};example.run();