Advertisement
Willcode4cash

Singleton Pattern

Aug 14th, 2016
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.94 KB | None | 0 0
  1. // In software engineering, the singleton pattern is a design pattern used to implement the mathematical
  2. // concept of a singleton, by restricting the instantiation of a class to one object. This is useful when
  3. // exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized
  4. // to systems that operate more efficiently when only one object exists, or that restrict the instantiation
  5. // to a certain number of objects.
  6.  
  7. public sealed class MySingleton
  8. {
  9.     private static MySingleton instance;
  10.     private static readonly Object sync = new object();
  11.  
  12.     private MySingleton()
  13.     {
  14.         // initialize members here
  15.     }
  16.  
  17.     public static MySingleton Instance
  18.     {
  19.         get
  20.         {
  21.             if (instance == null)
  22.             {
  23.                 lock (sync)
  24.                 {
  25.                     if (instance == null)
  26.                         instance = new MySingleton();
  27.                 }
  28.             }
  29.  
  30.             return instance;
  31.         }
  32.     }
  33.    
  34.     public void SayHello()
  35.     {
  36.         Console.WriteLine("Hello!");
  37.     }
  38.    
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement