Advertisement
bero_0401

Singleton Pattern

Oct 3rd, 2024
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.07 KB | Source Code | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace revision
  8. {
  9.     internal class TestSingleton
  10.     {
  11.         // Make the constructor private
  12.         private TestSingleton() {
  13.             // Only First time you call the instnce object it execute the constructor  
  14.             Thread.Sleep(3000);
  15.            
  16.         }
  17.         public static object _lock = new();
  18.  
  19.         // private instance of the class
  20.         private static TestSingleton _instance;
  21.  
  22.  
  23.         // public method to intialize that instance
  24.         public static TestSingleton Instance {
  25.             get {
  26.  
  27.                 lock (_lock) // /to avoid multi threads to create the instance at the same time
  28.                 {
  29.                     if (_instance == null)
  30.                     {
  31.                         _instance = new TestSingleton();
  32.                     }
  33.                 }
  34.                 return _instance;
  35.             }
  36.         }
  37.  
  38.         public int Add(int x, int y)
  39.         { return x + y; }
  40.  
  41.     }
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement