6 June 2011

Singleton Class in C# with Example

Singleton class in C#

What is Singleton class?
A class that has only one instance, and you need to provide a global point of access to the instance.

How to achieve Singleton class?
Singleton provides a global, single instance by:
1. Making the class create a single instance of itself.
2. Allowing other objects to access this instance through a class method that returns a reference to the instance.A class method is globally accessible.

3. Declaring the class constructor as private so that no other object can create a new instance.

Uses of Singleton Class
1. The static initialization approach is possible because the .NET Framework explicitly defines how and when static variable initialization occurs.
2. The Double-Check Locking idiom described earlier in "Multithreaded Singleton" is implemented correctly in the common language runtime.

Demerits of Singleton Class
If your multithreaded application requires explicit initialization, you have to take precautions to avoid threading issues.

Singleton class vs. Static methods

1.Static classes don’t promote inheritance. If your class has some interface to derive from, static classes makes it impossible.
2.You cannot specify any creation logic with static methods.

When to User Singleton Class?
The below activities is common through out the application, Singleton increase the performance of the application

1. Logging
2. Database Access
3. Reading Configuration information.

Singleton provides a global, single instance by:

1. Making the class create a single instance of itself.
2. Allowing other objects to access this instance through a class method that returns a reference to the instance.
3. A class method is globally accessible.
4. Declaring the class constructor as private so that no other object can create a new instance.

The following implementation of the Singleton design pattern follows the solution presented in Design Patterns: Elements of Reusable Object-Oriented Software [Gamma95] but modifies it to take advantage of language features available in C#, such as properties:

The class is marked sealed to prevent derivation, which could add instances.

The instantiation is not performed until an object asks for an instance; this approach is referred to as lazy instantiation. Lazy instantiation avoids instantiating unnecessary singletons when the application starts.

Example :

using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}


Static Initialization of Singleton Class
One of the reasons Design Patterns [Gamma95] avoided static initialization is because the C++ specification left some ambiguity around the initialization order of static variables. Fortunately, the .NET Framework resolves this ambiguity through its handling of variable initialization:

Example:
public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();
 
   private Singleton(){}

   public static Singleton Instance
   {
      get
      {
         return instance;
      }
   }
}

The main disadvantage of this implementation, however, is that it is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created. Each thread could execute the following statement and decide that a new instance has to be created.

Multithreaded Singleton in C#

Static initialization is suitable for most situations. When your application must delay the instantiation, use a non-default constructor or perform other tasks before the instantiation, and work in a multithreaded environment, you need a different solution. Cases do exist, however, in which you cannot rely on the common language runtime to ensure thread safety, as in the Static Initialization example. In such cases, you must use specific language capabilities to ensure that only one instance of the object is created in the presence of multiple threads.

This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires this type of implementation. In most cases, the static initialization approach is sufficient.

using System;
public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            lock (syncRoot)
            {
               if (instance == null)
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks.

This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires this type of implementation. In most cases, the static initialization approach is sufficient.

No comments:

Post a Comment

Comments Welcome