Friday, May 26, 2017

Singleton Design Pattern

In some situation we need one instance can share and serve globally in whole application , so to solve this problem we can use singleton design pattern.
  • A singleton class constructor is private and without parameter.
  • The singleton class is sealed
Following is the simple way to create a singleton class.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SingletonDesignPattern
{
    public sealed class SingletonClass
    {
        private SingletonClass()
        {

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

by this way with the help of this pattern we can always get the single instance of the class object and share in whole application globally.
Problem with this implementation
This is not thread safe in multi thread environment. two thread can simultaneously read the statement "if (instance == null)" and both get instance is null and both thread created two memory.
we will read this in next post



Reference
http://www.csharpstar.com/singleton-design-pattern-csharp/
http://www.c-sharpcorner.com/UploadFile/8911c4/singleton-design-pattern-in-C-Sharp/
http://csharpindepth.com/Articles/General/Singleton.aspx, https://msdn.microsoft.com/en-us/library/ff650316.aspx