@tusss/ood
    Preparing search index...

    Function Singleton

    • A class decorator / mixin function that implements the Singleton design pattern.

      It wraps the provided class constructor and returns a subclass that contains a static instance property, guaranteeing that only one instance of the class will be created and shared.

      Type Parameters

      • T extends Constructor

        The constructor function type of the class to be turned into a Singleton.

      Parameters

      • cls: T

        The class constructor function.

      Returns { prototype: __type<any>; get instance(): InstanceType<T>; new (...args: any[]): __type } & T

      A subclass extending the input class, equipped with a static instance getter.

        • new (...args: any[]): __type
        • Parameters

          • ...args: any[]

          Returns __type

      • prototype: __type<any>
      • get instance(): InstanceType<T>

        Gets the shared, lazily-instantiated instance of the class.

      Example demonstrating wrapping a class with Singleton and accessing its shared instance

      class DatabaseConnection {
      connect() {
      console.log("Connected to DB");
      }
      }

      const DbSingleton = Singleton(DatabaseConnection);

      // Accessing the shared instance
      const db1 = DbSingleton.instance;
      const db2 = DbSingleton.instance;

      console.log(db1 === db2); // true