Refinance now before rates go up! Get multiple rate quotes at GetMyLender.com.

Singleton Pattern In C Sharp

What is Singleton Pattern ?

Singleton pattern is one of the simplest design patterns. This pattern ensures that a class has only one instance and provides a global point of access to it.

History of Design Patterns :

Singleton pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net.

In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book (Design Patterns : Elements of Reusable Object-Oriented Software) for explaining the concept of Design Pattern in Software development. These four authors are collectively known as Gang of Four (GOF).

The 23 Design patterns are defined by the Gang of Four programmers. These 23 patterns are divided into three groups depending on the nature of the design problem they intend to solve.

Groups are 1) Creational Design Patterns 2) Structural Design Patterns 3) Behavioral Design Patterns.

Out of these three groups, singleton is the Creational Design Patterns.


Description :

As we already discussed in first line, Singleton is the combination of two essential properties:

i) Ensure a class only has one instance

ii) Provide a global point of access to it

What we need?

1) A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern).

2) The class with sealed. So that it prevents subclassing.

3) A static variable which holds a reference to the single created instance, if any.

4) A public static method for getting the reference to the single created instance, creating one if necessary. public static property Instance as the means of accessing the instance. In all cases, the property could easily be converted to a method.

By using above information we can write code as like follows:
            
                using System;

                public sealed class Singleton
                {
                    private static Singleton instance=null;
                
                    private Singleton()
                    {
                    }
                
                    public static Singleton Instance
                    {
                        get
                        {
                            if (instance==null)
                            {
                                instance = new Singleton();
                            }
                            return instance;
                        }
                    }
                }
            
        
But it’s a bad coding because it is not thread-safe.

Suppose we have two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Thread-safety using double-check locking

            
                using System;

                public sealed class Singleton
                {
                   private static volatile Singleton instance;
                   private static object sourceLock  = new Object();
                
                   private Singleton() {}
                
                   public static Singleton Instance
                   {
                      get 
                      {
                         if (instance == null) 
                         {
                            lock (sourceLock ) 
                            {
                               if (instance == null) 
                                  instance = new Singleton();
                            }
                         }
                
                         return instance;
                      }
                   }
                }
            
        

Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed.

We have created an instance of object named sourceLock , its role is to allow only one thread to access the code nested within the lock block at a time. So once a thread enter the lock area, other threads need to wait until the locking object get released so, even if multiple threads try to access this method and want to create an object simultaneously, it's not possible. Further only if the static instance of the class is null, a new instance of the class is allowed to be created.

Hence only one thread can create an instance of this Class because once an instance of this class is created the condition of singleTonObject being null is always false and therefore rest all instance will contain value null.

Thread-safe without using locks

            
                using System;

                public sealed class Singleton
                {
                    private static readonly Singleton instance = new Singleton();
                
                    // Explicit static constructor to tell C# compiler
                    // not to mark type as before field init
                    static Singleton()
                    {
                    }
                
                    private Singleton()
                    {
                    }
                
                    public static Singleton Instance
                    {
                        get
                        {
                            return instance;
                        }
                    }
                } 
            
        

Real World Example of a Singleton Class

1) Mouse object is using singleton design pattern.

2) Thread pools, SQL Connection Pools, Registry objects, Objects handling user preferences, Caches, Factory classes, Builder classes and Statistics utilities like a hit counter, log4net - when you call its logger, it uses a singleton class to return it.


No comments:

Post a Comment