DCSIMG
Singleton Pattern - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2012 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

Singleton Pattern

Singleton Pattern

The first pattern in the creational pattern series is the singleton pattern.
You can read my previous posts about design patterns here:
Structural patterns
Decorator pattern 
Proxy pattern
Facade pattern
Adapter pattern
Composite pattern
Bridge pattern
Flyweight pattern

Introduction
The singleton pattern is a very useful pattern.
I encountered it while I was a second year student in an object oriented
course I took. During that course we had a lecture about design patterns and
the singleton pattern was one of the patterns that were discussed.
Think about it, one lecture about design patterns in a course about object oriented...

What is the Singleton Pattern?
The singleton pattern ensures that a class has one instance only.
Also, it provides the access point to the get the that single instance.
For a UML diagram of the pattern go to dofactory site.

Example in C#
How does it works? lets look at an example:

    class Singleton

    {

        #region Members

 

        // the only instance of the singleton object

        private static Singleton _me;

 

        // lock synchronization object

        private static object syncLock = new object();

 

        #endregion

 

        #region Properties

 

        /// <summary>

        /// Get the instance of the singleton

        /// </summary>

        public static Singleton Instance

        {

            get

            {

                // handle the creation only once and if

                // needed also the implementation is

                // thread safe

                if (_me == null)

                {

                    lock (syncLock)

                    {

                        if (_me == null)

                        {

                            Singleton newInstance = new Singleton();

                            System.Threading.Thread.MemoryBarrier();

                            _me = newInstance;      

                        }

                    }

                }

 

                return _me;

            }

        }

 

        #endregion

 

        #region Ctor

 

        private Singleton()

        {

        }

 

        #endregion

 

The implementation is thread safe. I lock the syncLock object and then create
the instance of the singleton only once. After that, the instance will be returned
every time it is being asked by the Instance property.
I added the MemoryBarrier call on the thread to correct the implementation
I made earlier thanks to the comment of Arnon. Look at the post of Eran Kampf for details.

Summary
To sum up the post, you should use the pattern whenever you need to be sure that only
single instance of a class is created. As I wrote the singleton is very useful.
Be aware that using a static object (the singleton object) has a performance issue
(because it is static) and therefore use the pattern carefully.
The next stop in the creational patterns - the abstract factory.

Comments

Arnon Rotem-Gal-Oz said:

The implementation you have is not thread safe

since you failed to mark _me as volatile

see www.ekampf.com/.../WhatsWrongWithThisCode1Discussion.aspx

and my blog:

www.rgoarchitects.com/.../SingletonInNET.aspx

# April 22, 2008 11:51 PM

Gil Fink said:

Thanks for your comment Arnon.

I corrected my implementation according to what Eran

wrote in his blog. I prefer his solution because of

the lazy loading issue. A lot of times the singleton objects are very heavy to load and therefore I prefer to load them on demand.

# April 23, 2008 9:39 AM

Arnon Rotem-Gal-Oz said:

You can still use the static readonly notation and get lazy loading if you do that in an inner class

as mentioned in (en.csharp-online.net/Singleton_design_pattern:_Thread-safe_Singleton)

public sealed class Singleton

{

  private Singleton() {}

  public static Singleton GetInstance()

  {

     return NestedSingleton.singleton;

  }

  class NestedSingleton

  {

     internal static readonly Singleton singleton = new Singleton();

     static NestedSingleton() {}

  }

# April 23, 2008 12:03 PM

Gil Fink said:

Yes.

I could use the solution you showed in your post but then instead of one class I'll have two classes to maintain. Sometimes what seems to be simple can make your system very complicated.

# April 24, 2008 9:28 AM

ekampf said:

Hey Kudos for the trackback :)

Both the use of a MemoryBarrier and the nested class are valid solutions that'll do the job (lazy thread-safe singleton) right.

So it comes down to the question of maintainability.

What will a developer not previously familiar with the code doing code inspection will make of either solution?

There's no right answer for that and with the right documentation they both should be fine.

I was kinda leaning towords the nested class solution at first but using it in my code left everyone in my project dazzled so I guess they're both equally confusing to the novice...

Regards,

Eran

# May 20, 2008 12:08 AM

Gil Fink said:

Thanks for your comment Eran.

I agree with what you wrote. Both solutions are good and you should choose the solution that you prefer (that doesn't confuse your collegues :-)).

# May 20, 2008 8:13 AM

Gil Fink on .Net said:

The post describe the chain of responsibility pattern and shows an example of how to use it in C#.

# July 12, 2008 1:23 PM