Tuesday, September 15, 2015

Real Time Example of Singleton Design Pattern

What is Singleton Design Pattern:

Singleton pattern ensures that a class has only one instance and provides a global access to it.


Code Implemented using C#

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

namespace SingletonSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton obj1 = Singleton.Instance();
            Singleton obj2 = Singleton.Instance();
            Singleton obj3 = Singleton.Instance();
            Singleton obj4 = Singleton.Instance();

            if (obj1 == obj2 && obj2 == obj3 && obj3 == obj4)
            {
                Console.WriteLine("Objects are the same instance");
            }

            // Wait for user
            Console.ReadKey();
        }
    }

    class Singleton
    {
        private static Singleton _instance;

        protected Singleton()
        {

        }

        public static Singleton Instance()
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }
}

Thursday, September 10, 2015

Singleton Design Pattern in C#


Singleton Design Pattern?

A Singleton Ensures a class has only one instance and provides a global point of access to it.
A single constructor, that is private and parameterless.
The class type is sealed.
A static variable that holds a reference to the single created instance, if any.
A public static means of getting the reference to the single created instance, creating one if necessary.

The important advantages of a Singleton Pattern are listed below:
  • Singleton can be lazy loaded.
  • Singleton helps to hide dependencies.
  • Singleton pattern can be implemented interfaces.
  • Singleton can be also inherit from other classes.
  • Singleton has Static Initialization.
  • Singleton provides a single point of access to a particular instance, so it is easy to maintain.
  • Singleton can be extended into a factory pattern.



Singleton Design Pattern Disadvantages 

  • Hard to switch for a mock object(Unit testing)
  • This pattern reduces the potential for parallelism within a program