SIGN UP MEMBER LOGIN:    
ARTICLE

Singleton Pattern - Creational Pattern

Posted by Man Mohan Sharma Articles | Design & Architecture January 19, 2011
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.
Reader Level:


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();
        }
    }

 

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Nevron Gauge for SharePoint
Become a Sponsor