Advertisement
sdfxs

Untitled

May 11th, 2021
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. class Counter {
  2. private static instance: Counter;
  3. private static count: number = 0;
  4.  
  5. private constructor() { }
  6.  
  7. public static getInstance(): Counter {
  8. if (!Counter.instance) {
  9. Counter.instance = new Counter();
  10. }
  11.  
  12. return Counter.instance;
  13. }
  14.  
  15. public getCount(): number {
  16. return Counter.count;
  17. }
  18.  
  19. public increment(): void {
  20. Counter.count++;
  21. }
  22. }
  23.  
  24. function clientCode() {
  25. const s1 = Counter.getInstance();
  26. const s2 = Counter.getInstance();
  27.  
  28. if (s1 !== s2) throw new Error('Singleton doesnt work');
  29.  
  30. s1.increment();
  31. console.log('s1:', s1.getCount());
  32. console.log('s2:', s2.getCount());
  33. }
  34.  
  35. clientCode();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement