Saturday, November 13, 2010

..........Singleton Pattern [CD]

Singleton pattern ensure that a class should have only one instance and provide a global access to that instance.

Example 1 Not thread safe

public sealed class Singleton
{
private static Singleton instance=null;

private Singleton()
{
}

public static Singleton Instance
{

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

Example 2 Thread safe

public sealed class Singleton
{
private static Singleton instance=null;
priavte readonly object objPadlock = new Object();

private Singleton()
{
}

public static SingletonInstance
{
get
{
//Otherwise Lock will execute each time even object already created, this is called double null
check condition.

if(instance ==null)
{
lock (padlock)
{
if (instance==null)
instance = new Singleton();
}//End of lock (padlock)
}//End of if(instance ==null)
return instance;
}
}

3. Thread safe without lock statement  using Nested class (Lazy Loading)

It is guaranteed that a static constructor in a C# class is called only once at most. If it only creates an
instance in the static constructor, there is one instance at most. A concise solution for the singleton

pattern with a static constructor is


public sealed class Singleton
{
    private Singleton()
    {
    }

    public static Singleton Instance { get { return Nested.instance; } }
        
    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

It is thread safe because of lazy loading.

5. Thread safe in .Net 4.0+

public sealed class Singleton
{
    private static readonly Lazy lazy =
        new Lazy(() =new Lazy(() => new Singleton());
    
    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

6. Not quite as lazy, but thread-safe without using locks using Static Constructor

It is guaranteed that a static constructor in a C# class is called only once at most. If it only creates an
instance in the static constructor, there is one instance at most. A concise solution for the singleton

pattern with a static constructor is

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

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    private Singleton()
    {
    }

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


7. Another way for singleton pattern



/// Sample singleton object.

public sealed class SiteStructure
{

/// This is an expensive resource we need to only store in one place.


object[] _data = new object[10];




/// Allocate ourselves. We have a private constructor, so no one else can.

static readonly SiteStructure _instance = new SiteStructure();




/// Access SiteStructure.Instance to get the singleton object.
/// Then call methods on that instance.

public static SiteStructure Instance
{
get { return _instance; }
}



/// This is a private constructor, meaning no outsiders have access.

private SiteStructure()
{
// Initialize members, etc. here.
}
}

8.  Using readonly and Sealed class

public sealed clas Sinhgleton
{

private static readonly Singleton instance = new Singleton();

private Singleton()
{
}

public static Singleton Instance
{

get
{
return instance;
}

}

The benefit of using this approach(Using Sealed) that no one can create object even by inheritance, Otherwise anyone can create object  by inheritance like

public class Singleton
    {
        int counter = 0;
        private Singleton()
        {
            Console.WriteLine(counter++);
        }

        static Singleton singleton = null;

        public static Singleton GetSingleton()
        {
            if (singleton == null)
            {
                singleton = new Singleton();
                return singleton;
            }
            else
                return singleton;
        }
     

        public class SingletonChild : Singleton
        {           

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Singleton obj = new Singleton.SingletonChild();

            Singleton obj1 = new Singleton.SingletonChild();

            if (obj.Equals(obj1))
            {

            }
        }
    }

  • Abstract Factory, Builder and Prototype can use singleton in their implementation.
  • Facade object are often singleton because only one object required.
  • They don't pollute the global namspace with unnecessary variables.
  • They permit lazy allocation and initialization where global variable in many languages consume resources.
  • HttpContext class in ASP .net implements singleton, object can be retried using HttpContext.Current
  • OperationContext Class in WCF implement singleton
  • Dispatcher class implements singleton



No comments:

Followers

Link