Monday, February 16, 2015

Singleton Pattern

Singleton is one of the simplest patterns which involved one class and it is responsible for instance itself to make sure it creates only one instance. And Singleton provides a global access point to access that instance. Singleton pattern is very useful when we want create only one instance of a class and used same instance of each call. Best example of Singleton is printer driver class.


There are three main things to implement a Singleton pattern.  
  1. A private constructor. Main objective to have a private constructor is to prevent the class initialization from outside.
  2. A static variable which holds the instance of the class.
  3. A static method which create an instance of the class if the static variable is empty. And return the instance of the class.
 
Below example will explain all about.

using System;

namespace TestSoln
{
    //Singleton implementation
    public class Singleton
    {
        //static variable which holds the instance of the class.
        private static Singleton _instance;

        //private constructor which prevent the class initialization from outside.
        private Singleton() { }

        //creates an instance of the class if the static variable is empty. And return the instance of the class.
        public static Singleton GetInstance()
        {
            if (_instance == null)
                _instance = new Singleton();
            return _instance;
        }

        public void DoSomething()
        {
            Console.WriteLine("I am a Singleton class method");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("--Start--");

            // calling Singleton class
            Singleton.GetInstance().DoSomething();
            Console.ReadLine();
        }
    }
}




Output:
--Start--                               
I am a Singleton class method