Singleton

Posted by Dustin Boston .


CAUTION

Construction Area
Watch out for:

  • Broken code
  • No comments
  • Partial examples
  • Missing tests

Source Code Listing

code.ts

// eslint-disable-next-line @typescript-eslint/no-extraneous-class
class Singleton {
  public static getInstance<T extends Singleton>(this: new () => T): T {
    // Generic to handle subclasses
    Singleton._instance ||= new this();

    return Singleton._instance as T;
  }

  private static _instance: Singleton | undefined = undefined; // Private static instance

  protected constructor() {
    // Protected constructor to prevent direct instantiation
    // Any initialization logic here
  }
}

class ExampleClass extends Singleton {
  private properties: Record<string, any> = {}; // Proper type for properties

  constructor(argument1: string, argument2: string) {
    super();
    console.log(argument1, argument2);
  }

  set(key: string, value: any): void {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    this.properties[key] = value;
  }

  get(key: string): any {
    return this.properties[key];
  }
}

const example = {
  run(): void {
    const example = ExampleClass.getInstance("arg1", "arg2"); // Type-safe instantiation
    example.set("Singleton", "This is a singleton value");
    console.log(example.get("Singleton"));

    const example2 = ExampleClass.getInstance("anotherArg1", "anotherArg2"); // Will return the same instance

    if (example === example2) {
      console.log("Both variables point to the same instance");
    }
  },
};

example.run();