Friday 13 April 2012

Singleton using C#


Inreoduction
This article intended to give brief overview of singleton pattern. Main intent to define single tone pattern is to ensure a class has only one instance and provide global point of access to it. One may think, this is not big deal, we can achieve same thing by declaring static class. Global static class solves one portion of global accessibility, but does nothing to ensure that single instance of a class running at a time. In singleton, responsibility of having single instance at a time should in a class itself not on the user class. User class should free from this responsibility.

User
Logical Model

                                                                                                     
As shown above, Singleton model is straight forward for understand. There is only one singleton instance. Client can access that instance through single well-known access point.

Physical Model

Physical model of singleton is also as simple as logical one. There are many different ways that singleton have implemented over time. Simple UML of GoF singleton is shown below




Using Code

Let’s understand singleton by defining a simple class as below:

    class MySingleton
    {
        private MySingleton() { }

        public static MySingleton CreateInstance()
        {
            if (singleton == null)
            {
                lock (typeof(MySingleton))
                {
                    if (singleton == null)
                        singleton = new MySingleton();
                }
            }
            return singleton;
        }
        private static MySingleton singleton = null;
    }

As shown above we’ve defined singleton class MySingleton. We can see here we define constructor as private constructor that means no one can create instance of this class explicitly. Only way for creating instance is static method CreateInstance(). While creating instance it check’s wether instance has been created before, if not then will create new instance else use previous one. Thus our class will handle responsibility of having single instance at a time. It seems good but may cause a problem in multi-threaded environment. If two threads manage to enter in control block at a same time, two instance of member variable could be created. To solve this one may put control block into crtical section to ensure thread safety, but by doing this each call for instance method will be serialized and cause negative impact on performance. To solve this we’ve to make little change in CreateInstance() method.

        public static MySingleton CreateInstance()
        {
            if (singleton == null)
            {
                lock (typeof(MySingleton))
                {
                    if (singleton == null)
                        singleton = new MySingleton();
                }
            }
            return singleton;
        }

Technique we used above called “Double Check Lock”. In this technique we didn’t introduce any new declaration or use any new variable, just we tack advantage of critical section here. The double check occurs at the first IF block. If the member variable is null, then the execution enters a critical section block where the member variable is double checked again. Only after passing this last test is the member variable instantiated. The general thinking is that there is no way that two threads can create two instances of the class using this technique. Also, since there is no thread blocking at the first check, most calls to this method would not get the performance hit of having to enter the lock.
Another way to attempt to fix this problem could be using the volatile keyword on the member variable declaration. This should tell the compiler to not reorder the code and forgo optimization. So our final code will be:

    class MySingleton
    {
        private MySingleton() { }

        public static MySingleton CreateInstance()
        {
            if (singleton == null)
            {
                lock (typeof(MySingleton))
                {
                    if (singleton == null)
                        singleton = new MySingleton();
                }
            }
            return singleton;
        }
        private static volatile MySingleton singleton = null;
    }

Conclusion

The Singleton design pattern is a very useful mechanism for providing a single point of object access in an object-oriented application. Regardless of the implementation used, the pattern provides a commonly understood concept that can be easily shared among design and development teams. However, as we have discovered, it is also important to note how different these implementations can be and their potential side effects. The .NET Framework goes a long way to help an implementer of a pattern design the type of functionality desired without having to deal with many of the side effects discussed in this article. The validity of the pattern's original intent is proven when implemented properly.

References
To know more about this pattern kindly follow following URLs


No comments:

Post a Comment