Advertisement
ggeorgiev88

private constructor()

Mar 15th, 2024
597
0
298 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Singleton {
  2.     private static instance: Singleton;
  3.  
  4.     private constructor() {
  5.         // Private constructor to prevent instantiation
  6.     }
  7.  
  8.     static getInstance(): Singleton {
  9.         if (!Singleton.instance) {
  10.             Singleton.instance = new Singleton();
  11.         }
  12.         return Singleton.instance;
  13.     }
  14.  
  15.     public someMethod(): void {
  16.         console.log("Some method called");
  17.     }
  18. }
  19.  
  20. // Usage
  21. const singletonInstance1 = Singleton.getInstance();
  22. const singletonInstance2 = Singleton.getInstance();
  23.  
  24. console.log(singletonInstance1 === singletonInstance2); // Output: true, there is only one instance
  25. singletonInstance1.someMethod(); // Output: Some method called
  26.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement