BorderLayoutBoxedLayoutOpenLayout Maximum textMedium textSmall text


Register
18 March 2010
 English (United Kingdom) English (United States)
   
Mar 21

Written by: Gary Woodfine
21/03/2008 20:55 

The singleton pattern is designed to restrict the instantiation of a class to one object. The advantage of doing this is that only one object is responsible for coordinating the actions across an application.

The singleton pattern though being one of the most basic software patterns suffers from being the most misused pattern, resulting in many people in the software industry referring to it as an anti pattern. An anti pattern is a design pattern that appears obvious but is ineffective or far from optimal in practice. In reality the singleton pattern could assist in improving an applications performance if it is implemented correctly and consideration is given to it’s use.

 

Static Initialization

image

The following illustration presents a very basic implementation of a singleton class.

public sealed class Singleton 
{
       private static readonly Singleton _instance = new Singleton();
       public Singleton() { }
       public static Singleton Instance
       {
           get
           {
               return _instance;
           }

       }
}

The instance of the class is created the first time any member of the class is referenced. The common language runtime (CLR)  takes care of the variable initialization. The class is marked sealed to prevent derivation, which could add instances. The above example implements a form of instantiation which is known as Lazy Instantiation. 

The only potential downside to this approach is that you are handing control of instantiating the member variable over to the CLR, so you are unable to initiate any checks on the member variable at instantiation time, however in most cases in creating a singleton method in C# this is the preferred method.

 

Multithreaded Singleton

Implementing a singleton class in a multi threaded environment adds a little more complication because you cannot rely on the CLR to ensure thread safety. In a multi threaded environment it is best to use C# language specific language capabilities to ensure that only one instance of the object is created in the presence of multiple threads.

image

public sealed class Singleton 
    {
        private static volatile Singleton _instance;
        private static readonly object _lock = new Object();
        private Singleton() { }
        public static Singleton Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                          _instance = new Singleton();
                    }
                }
                return _instance;
            }
        }

This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a _lock instance to lock on, rather than locking on the type itself, to avoid deadlocks.

This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires this type of implementation. In most cases, the static initialization approach is sufficient.

Singleton Pattern  VS Static class

Although aesthetically  static classes and the singleton pattern  appear to provide the same type functionality , providing a mechanism for  sharing of redundant objects in memory. There is however differences in the implementation.  There advantages and disadvantages to both these solutions and it is entirely dependent on the situation in which you need to implement either.  A big difference between Static classes and singletons is that Static classes cannot implement interfaces and you cannot pass a static class as if it were just another implementation.

 

Advantages of Singletons

  • Singleton classes can extend classes and implement interfaces
  • Singleton classes can be initialised lazily or asynchronously.
  • Singleton classes can be extended and it’s methods can be overridden
  • Singleton classes can be handled polymorphically without forcing their users to assume that there is only one instance.

Keep grinding  the code,

Gary

Recommended Reading

     

Tags:

4 comment(s) so far...

Re: Singleton Pattern

Your post is incorrect- the first Singleton is perfectly thread safe. See www.yoda.arachsys.com/csharp/singleton.html (see Fourth version). Maybe you are getting confused with the Java double checked locking problem.

By Anon on   23/06/2009 09:40

Re: Singleton Pattern

Thank you so much for your feedback. It really is appreciated. However I think you may be slightly wrong too. I would urge you to read the article you have cross referenced in it's entirety, you will notice that the author does include some caveats as to thread safety too. I do however realise there may be some room for debate here.I have used Microsoft MSDN as the source of my blog post, msdn.microsoft.com/en-us/library/ms998558.aspx , I will be ammending my article later today with some form of proof of concept project to better illustrate which mehtod is better. Unitl then I refer you too. . It probably provides more weight behind my samples.Again thank you for your feedback, it has prompted me to further enhance my post. I had initially placed this up here for a reminder to myself. --Update I have re-read my post several times and I can't find where I have said that the lazy instantiation is not thread safe? All I said is that CLR is responsible for preforming checks?

By Gary Woodfine on   23/06/2009 13:41

Re: Singleton Pattern

Hi Gary

I might be missing something basic here, but according to msdn.microsoft.com/en-us/library/ms954629.aspx (pls see the last singleton code - .NET example - ) something similar to your first implementation should be thread safe. I am also a bit confused cause the msdn article you point to, raises questions about multitheading for your first singleton, however the article i refer to seems to argue otherwise.

Thanks

By Dimitri on   11/08/2009 21:24

Re: Singleton Pattern

Dimitri,Thank you for your query. There is definetely a little confusion regarding implementation of design patterns. As the article, you provided a link for, points out the .NET framework actually takes care of the "double check locking" problem for you in the lazy instantiation, and in most cases this will suffice when creating singletons. However there are certain situations when developing multi threaded applications that a little extra attention to how the singleton pattern is implemented may be required.

I really must try find some time to update this article a bit :-)

By Gary Woodfine on   11/08/2009 21:56

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment   Cancel 


Copyright 2010 by Three Nine Consulting