Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. namespace SingletonPattern {
  2. export class Singleton {
  3. // A variable which stores the singleton object.
  4. // Initially, the variable acts like a placeholder
  5. private static sharedInstance: Singleton;
  6.  
  7. public id: number;
  8.  
  9. // Private initialization to ensure just one instance is created.
  10. private constructor() {
  11. console.log("Initialized.")
  12. this.id = Math.random();
  13. }
  14.  
  15. // This is how we create a singleton object
  16. public static getInstance(): Singleton {
  17. // Check if an instance of the class is already created.
  18. if (!Singleton.sharedInstance) {
  19. // If not created create an instance of the class, and store the instance in the variable
  20. Singleton.sharedInstance = new Singleton();
  21. }
  22. // return the singleton object
  23. return Singleton.sharedInstance;
  24. }
  25.  
  26. public sayHi(): void {
  27. console.log("Hi!");
  28. }
  29. }
  30. }
  31.  
  32. const instance1 = SingletonPattern.Singleton.getInstance();
  33. instance1.sayHi();
  34. console.log(instance1.id);
  35.  
  36. const instance2 = SingletonPattern.Singleton.getInstance();
  37. console.log(instance2.id);
  38.  
  39. //However, js gives you ability to do next:
  40. console.log("🤔")
  41. const test1 = new SingletonPattern.Singleton();
  42. console.log(test1.id);
  43. test1.sayHi();
  44.  
  45. const test2 = new SingletonPattern.Singleton();
  46. console.log(test2.id);
  47. test1.sayHi();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement