Singleton class

    0

    0

    Giovanny Gongora

    Codiga's TypeScript Recipes

    Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.

    export class Singleton {
      // A variable that stores the singleton object. Initially,
      // the variable acts like a placeholder
      private static singleton: Singleton;
      // private constructor so that no instance is created
      private constructor() {
      }
      // This is how we create a singleton object
      public static getInstance(): Singleton {
        // check if an instance of the class is already created
        if (!Singleton.singleton) {
          // If not created create an instance of the class
          // store the instance in the variable
          Singleton.singleton = new Singleton();
        }
        // return the singleton object
        return Singleton.singleton;
      }
    }
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.