Singleton Pattern - Creational Pattern


Singleton Pattern:

This is a part of the Creation Pattern. This pattern ensures that you have only one instance and provides a single point of contact to access the instance.

As per of GOF Definition:

Ensure a class has only one instance and provide a global point of access to it.

UML Class Diagram:

UML.gif

Singleton Class:

  1. This class is creating the instance at the beginning of the application, which makes the class thread safe, as it's already containing a readymade instance; for this, a static private variable to hold the single instance of the singleton class that returns the same instance on each call.

    private static MathUtility _instance = new MathUtility();
     
  2. This class has a private constructor to avoid the creation of more instances.

    private MathUtility() { }

    Complete Code:

    namespace SingletonReadyToUseInstanceAtBeginning
    {
        public class MathUtility
        {
            private static MathUtility _instance = new MathUtility();

    //Constructor should be private to avoid the further instance creation, as this class is already have an instance.
            private MathUtility() { }

           //Create a static propery to get the already created instance of this class.
            public static MathUtility Instance
            {
                get
                {
                    return _instance;
                }
            }

            private int _firstInput;
            public int FirstInput
            {
                get { return _firstInput; }
                set { _firstInput = value; }
            }

            private int _secondInput;
            public int SecondInput
            {
                get { return _secondInput; }
                set { _secondInput = value; }
            }

            public int Add()
            {
                 return _firstInput + _secondInput;
            }
        }
    }


Main Program:
  1. This class will create the two instances of singleton class.
  2. It will compare the both instance to see whether the both instances are equal or not.

                if (mathUtilInstance1 == mathUtilInstance2)
     
  3. It will also compare the values that will set in first instance and use in second instance.

    mathUtilInstance1.FirstInput = 1;
                mathUtilInstance1.SecondInput = 2;
                Console.WriteLine("Addition Value from Second Instance: {0}", mathUtilInstance1.Add());

    static void Main(string[] args)
            {
         MathUtility mathUtilInstance1 = MathUtility.Instance;

                mathUtilInstance1.FirstInput = 1;
                mathUtilInstance1.SecondInput = 2;

                Console.WriteLine("Addition Value from First Instance: {0}", mathUtilInstance1.Add());

                MathUtility mathUtilInstance2 = MathUtility.Instance;

                Console.WriteLine("Addition Value from Second Instance: {0}", mathUtilInstance1.Add());

                if (mathUtilInstance1 == mathUtilInstance2)
                {
                    Console.WriteLine("Both Instance are equal");
                }

                Console.ReadLine();
            }


Now look at the second version; I have done only slight modification here, this second version is called Lazy Instantiation i.e. the instance is not created until it is needed. This is good if your class is only used on rare occasions and has a decent memory footprint.
  1. You will notice in the code below that we again have the static private variable but this time it is not set to a new instance.

    private static MathUtility _instance;
     
  2. And we have the same empty private constructor.
     
  3. The Instance property has thread synchronization i.e. lock (typeof(MathUtility)). This will ensure that only one thread accesses the code at a time. This property will verify the instance, it will return the same instance if already created, otherwise it will create a new instance.

    class MathUtility
        {
            private static MathUtility _instance;
            //Constructor should be private to avoid the instance creation.
            private MathUtility() { }

            //Create a propery, this propery will return the instance if this is not already created
            public static MathUtility Instance
            {
                get
                {
                    lock (typeof(MathUtility))
                    {
                        if (_instance == null)
                        {
                            _instance = new MathUtility();
                        }
                        return _instance;
                    }
                }
            }

            private int _firstInput;
            public int FirstInput
            {
                get { return _firstInput; }
                set { _firstInput = value; }
            }

            private int _secondInput;
            public int SecondInput
            {
                get { return _secondInput; }
                set { _secondInput = value; }
            }
            public int Add()
            {
                 return _firstInput + _secondInput;;
            }
        }


Main Program:

This program will again ensure for the instance equality, by comparing instances and values.

class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Main Program Starts");
           
           
            MathUtility mathUtilInstance1 = MathUtility.Instance;

            mathUtilInstance1.FirstInput = 1;
            mathUtilInstance1.SecondInput = 2;

            Console.WriteLine("Addition Value from First Instance: {0}", mathUtilInstance1.Add());

            MathUtility mathUtilInstance2 = MathUtility.Instance;

            Console.WriteLine("Addition Value from Second Instance: {0}", mathUtilInstance1.Add());

            if (mathUtilInstance1 == mathUtilInstance2)
            {
                Console.WriteLine("Both Instance are equal");
            }

           
            Console.ReadLine();
        }
    }

 

Up Next
    Ebook Download
    View all
    Learn
    View all