Monday, 5 September 2011

Unique instance using Singleton pattern

For my recent project which my colleague was in charge, I faced a question on How to restrict a class from creating multiple instances.
After five minutes of R&D I came across a word "Singleton". I referred a bulky book from shelf and rolled down until this word signalled my brain "Singleton Pattern".

1) What is a singleton pattern? 
2) Why is it used for? 
3) How to implement?

1) What is singleton pattern?
A: In software engineering this is a design pattern used to restrict instantiation of a class to one object. In another point of view, we make one and only one instance of a class during runtime. The same instance will be resused throughout the life cycle untile exclusively destroyed.

2) Why is it used for?
A: Depends on the requirement.

In my application the singleton was used to keep only one instance until EOD(End Of Day). For which I used a static (C#.Net)/shared(VB.Net) method instead of giving access to constructor.
eg: If you want all the users to use the only instance of a class for all purposes(transactions in my case), this is the right choice.

3) How to Implement?
A: Remember the following points 
  1. Declare the default and all overridden constructors with private access specifier.
  2. Create a static(C#.Net)/shared(VB.Net) function which will take care of instantiation of a new object.
  3. You use only the static method to create a new instance, use of keyword 'new' will be restricted in this case.
SOURCE CODE AND DESIGN

In the windows form there are two buttons
a) Get : Calls the unique instance method.
b) Destroy : Destroy the unique instance created for a new creation.

My Singleton class

public class SingletonClass
    {
        private static SingletonClass MySingletonClass;
        
        string _szValue = "";
        //use this if you have any custom constructor
        private SingletonClass(string szValue)
        {
            _szValue = szValue;
        }

        //This is how you restrict an instance is created outside this class using keyword NEW
        private SingletonClass()
        {

        }

        public string szDate
        {
            get;
            set;
        }

        ///The function handles creation of a new instance of this class.
        ///A new instance is created only if there is no previous instances created.
        public static SingletonClass UniqueInstance(string szValue)
        {
            if (MySingletonClass == null)
            {
                MySingletonClass = new SingletonClass(szValue);
                MySingletonClass.szDate = DateTime.Now.ToString();
            }
            return MySingletonClass;
        }

        public static void DestroyInstance()
        {
            MySingletonClass = null;
        }
    }

Form1 code behind

        ///Button click event of Get.
        ///Returns date at which instance was initially created. 
        private void btnGet_Click(object sender, EventArgs e)
        {
            ///The most important point is this.
            ///Instead of declaring it using keyword new, you call the function.
            ///ie, we are avoiding SingletonClass mysingleton = new SingletonClass() 
            SingletonClass mysingleton = SingletonClass.UniqueInstance("hello");
            MessageBox.Show(mysingleton.szDate);
        }

        private void btnDestroy_Click(object sender, EventArgs e)
        {
            SingletonClass.DestroyInstance();
        }


No comments:

Post a Comment