SIGN UP MEMBER LOGIN:    
ARTICLE

Singleton Design Patterns in C#

Posted by Prasoon Articles | Design & Architecture June 08, 2009
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.
Reader Level:


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.

Login to add your contents and source code to this article
Article Extensions
Contents added by Kanaiyalal Prajapati on Jun 11, 2009
>"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."

Can you explain it?


A class of which only a single instance can exist and this class cannot support cloning method.




share this article :
post comment
 

Please , don't take it as personal comment. It is more of Constructive feedback that comment.
I am very sorry to say that this article is very ambigious . It is leading me no where. Introduction of article is itself not clear. 

One more thing , in all  you are saying "In My Next Article". Please complete  A to Z of an topic in same article. That would be very helpful for the readers like me. 

Thanks 
Dhananjay K 

Posted by Dhananjay Kumar Jun 17, 2009
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Nevron Gauge for SharePoint
Become a Sponsor