Singleton Design Patterns in C#



Whenever we want that a class has only one instance and it should have global point to access it but allowing the flexibility to create more objects if the situation changes in that case we will use Singleton Design Pattern.

Singleton design Pattern falls in the category of Creational Design Pattern.

Though the reason seems to be quite easy when to use Singleton design Pattern, the difficulty lies in choosing the class that we want to behave as Singleton. More on this I will explain in my next article.

But there might be few situations when we are forced to implement Singleton Design Pattern. One of those situations can be related to Licensing agreement where we are allowed to have only one connection per License agreement. In these type of scenarios, if multiple instances are created then Exception related to License agreement can be thrown. I have faced this while implementing a Pop3 client. In this case, the class where Pop3 client object is initialized must implement Singleton Design Pattern.

As of now I will just concentrate on how to implement Singleton Design Pattern once we have decided on the class to have above kind of property. 

Implementation of  Singleton Design Pattern :-

Singleton Design Pattern can be implemented in two ways :-

1. Field Initialization :-

In the first approach we have initialized the  _testsingleton in the field declaration only. Though from the code perspective this is perfectly legal that is no compilation error is generated, it has certain drawbacks which are listed as follows:-

  1. Even when not needed, one instance is created even when they are not absloutely needed.
  2. We don't have control on when to initialize it. It means that we might want to create an instance only when some network connectivity is established or all the resources has been acquired for the Application to run. 
Code Snippet :- 

using System;

namespace Test

{

    public class TestSingleton

    {

        private static TestSingleton _testsingleton = new TestSinleton();  // Field Intialization

 

        //  Constructor is private here to  to prevent instantiation by outside 

 

        private TestSingleton()

        {

            // construct object . . .

        }

 

        //A Public Method is exposed to the ouside world to get an instance only if no

 

        // of this class is created 

 

        public static TestSingleton GetInstance()

        {

            if (_testsingleton == null)

            {

                _testsingleton = new TestSingleton();

            }

            return _testsingleton;

        }

    }

}
2. Lazy Initialization :-

In this second approach, we will not initialize the object while declaration but only when it is being called or needed.


This approach has certain advantage :-

We may want to initialize this object only once certain things has happened like may be application 
has to wait for certain things to happen and only then it may have to initialize the object. That is if we have not have enough information to initiate a singleton at static initialization time we should go for Lazy Initialization. 

Code Snippet :-

using System;

 

namespace Test

{

    public class TestSingleton

    {

        private static TestSingleton _testsingleton; // Only Field Declaration

        private static Object _testLock = typeof(TestSingleton); //This is needed in Multithreaded 

        // Environment

 

        private TestSingleton()

        {

            // construct object . . .

        }

 

        // Initializtion is done only in this method

        public static TestSingleton GetInstance()

        {

            lock (_testlock) //  Give Lock to a Particular Thread.Till this Lock is not acquired by

            // Second thread, it can intantiate the singleton object.

            {

                if (_testsingleton == null)

                {

                    _testsingleton = new TestSingleton();

                }

                return _testsingleton;

            }

        }

    }

}

More on Singleton in my next article.

Up Next
    Ebook Download
    View all
    Learn
    View all