29 May 2015

singleton design pattern

While learning design patterns people start with singleton pattern, as it is the easiest pattern to understand and implement. Today let's see what is singleton pattern and how to implement singleton pattern in c# .NET

What is singleton pattern

  • Singleton is a creational design pattern which dealing with creation of objects of classes.
  • Intent of singleton design pattern: Singleton patterns ensures only one instance of an object is created in an application.

When to use singleton pattern

When creating an instance of a type is a costly affair in terms of CPU, Memory and time required, consider using Singleton pattern provided you don't want more than one instance of type at given point of time in your application. Normally application level objects are made singleton where we don't want the overhead of creating multiple instances and single instance is enough to get things done.

So in such scenario applying singleton pattern convey the developer intent clearly to colleagues on the project. So your intent of restricting to only one instance of a type is broadcasted clearly.

Singleton implementation in c#.NET

public class BussinessManager
 {
  private static BussinessManager bussinessManager;
  private static Object syncObject = new Object();

  private BussinessManager()
  {
  }

  public static BussinessManager GetInstance()
  {
   if (bussinessManager != null)
    return bussinessManager;

   lock (syncObject)
   {
      // Double NULL check to ensure object 
      // is not created by other thread.
    if (bussinessManager == null)
        bussinessManager = new BussinessManager();
   }
   return bussinessManager;
  }
 }

Using singleton class

BussinessManager manager = BussinessManager.GetInstance();
manager.Method1();

Highlights of singleton implementation

  • The singleton constructor is made private, so an instance of BussinessManager can be created only inside its class. Trying to create an instance outside the class will result in compilation error.

    BussinessManager.BussinessManager()' is inaccessible due to its protection level

  • GetInstance() is a static method. No need to create an instance of singleton class to invoke GetInstance() method.
  • 'syncObject' is used to synchronize the multiple threads trying to create get singleton instance. Locking on the 'syncObject' as shown in the above C# implementation ensures only one instance gets created even in multi-thread scenario.

What is bad with singleton pattern

Some people say singleton is an anti-pattern. This is because while unit testing, you are required to clear/reset of the singleton object state at the start of every unit test. When you run your unit tests simultaneously, the result of the unit tests may be different every time you run them.

No comments:

Post a Comment