Singleton Design Pattern – C#

source article: http://www.dotnet-tricks.com/Tutorial/designpatterns/L2KL080613-Singleton-Design-Pattern—C#.html

 

  1. //eager initialization of singleton
  2. public class Singleton
  3. {
  4.   private static Singleton instance =  new Singleton();
  5.   private Singleton() { }
  6.   public static Singleton GetInstance
  7.   {
  8.      get { return instance; }
  9.    }
  10.  }
  11. }
  12. //lazy initialization of singleton
  13. public class Singleton
  14. {
  15.   private static Singleton instance = null;
  16.   private Singleton() { }
  17.   public static Singleton GetInstance
  18.   {
  19.      get
  20.      {
  21.          if (instance == null)
  22.              instance = new Singleton();
  23.          return instance;
  24.        }
  25.    }
  26. }
  27.  
  28. //Thread-safe (Double-checked Locking) initialization of singleton
  29. public class Singleton
  30. {
  31.    private static Singleton instance = null;
  32.    private Singleton() { }
  33.    private static object lockThis = new object();
  34.    public static Singleton GetInstance
  35.   {
  36.     get
  37.     {
  38.         lock (lockThis)
  39.         {
  40.             if (instance == null)
  41.                 instance = new Singleton();
  42.             return instance;
  43.         }
  44.     }
  45.   }
  46. }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s