Friday, April 19, 2013

Singleton Design Pattern C# Example

Singleton is one of the most frequently used Design Patterns in Software Engineering. You should apply Singleton pattern if you want to ensure that your class will have only one instance with a global point of access to it.

Let's look at Singleton code:
public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();
   
   private Singleton(){}

   public static Singleton GetInstance
   {
      get 
      {
         return instance; 
      }
   }
}
As you can see the code is pretty simple. Class is defined as sealed in order to prevent derivation. Also Singleton variable is marked readonly, which means that it can be assigned only during static initialization or in a constructor.
This approach has only one downside - it's not thread safe. This code must be improved if you work in multithreaded environment.

Here is a thread safe version of Singleton:
public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object sync = new Object();

   private Singleton() {}

   public static Singleton GetInstance
   {
      get 
      {
         if (instance == null) 
         {
            lock (sync) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}
In this version of Singleton we resolved thread concurrency problems, so you can use it in multithreaded environment.

3 comments:

  1. I do a lot of web design using several languages but C sharp has always been there to help me, and you have been super useful thanks bud!

    ReplyDelete
  2. Thanks for a nice and clear example on this article and every article I've read so far on the site! -N

    ReplyDelete
  3. Double Null Singleton pattern is a bad idea, it can easily fail due to compiler optimization, check the following

    http://csharpindepth.com/Articles/General/Singleton.aspx

    ReplyDelete