Today we'll have a look at a well known pattern, the Singleton Pattern. Most people have already heard about this one.

The definition: "Ensure a class has only one instance and provide a global point of access to it."

Why would you want to only have one instance of a class?

Well, you could have one Configuration class for example, which reads some configuration settings at runtime, after which they remain available to your application.

It makes sense to only have one instance of this class, since having multiple could cause you to suddenly end up with different configuration settings.

Now, there are different Singleton Pattern implementations out there, which makes it interesting to have a look at it anyway.

First of all, let's look at the basics of how a Singleton works. Since we're working with our game example, a good singleton would be a reference to our hardware, the GraphicsCard, we should have only one instance of it, who knows what would happen if we start mixing up various instances :)

To make sure there is only one instance of a certain class, we let that class itself manage it's instantiation, instead of creating it ourselves using the new() operator.

Preventing others from calling new() on our class is done by making the constructor private. This way nobody can instantiate the class directly.

But how do we get an instance back then?

We provide a static method in the class itself, returning an instance of itself. By doing this, we can create one instance upon the first request and keep returning the same instance upon further requests.

This is also a form of lazy loading, since it only gets created when it is requested for the first time.

Basic Singleton

Where's the catch you might ask? Multi-threading! This simple implementation of a Singleton is not thread-safe!

It is possible for multiple threads to both execute the null check together, both evaluate it to true, since there is no instance yet, and then both threads create an instance, ending up with multiple instances instead of one.

Luckily, there's a solution. I'll cut straight to the point and give the thread-safe, lazy loading version. There are other thread-safe implementations out there, which you can read more about at Implementing the Singleton Pattern in C#.

Thread-Safe Singleton

As you can see, the actual instance is held inside a private sealed nested class, which is inside the GraphicsCard class. When the Instance property is called for the first time, it will instantiate a GraphicsCard in a thread-safe way, thanks to the Nested class, and upon subsequent requests, the same instance will be returned.

It's elegant, and doesn't use any special language keywords like lock() in C# or synchronize in Java.

I think it's quite easy to set up a Singleton like this, once you've done it once, you can do it everywhere.

With C# and generics however, we can be even more lazy, which is why I tried out throwing the Singleton Pattern into the following code.

Generic Thread-Safe Singleton

Now the only thing we need to do when we want to create a singleton is create a class, inheriting from Singleton passing the class itself in as the generic T.

The usage of both classes is identical afterwards, as you can see from this small snippet:

Singleton Usage

That's it, one of the easiest to understand patterns conceptually, but with some common pitfalls when implementing it.

There is one big issue bothering me with the generics approach however, hopefully someone can help me out on this, in an elegant way.

As it is coded right now, you can do new GraphicsCardGeneric(), which is something I don't want, since you run the risk of ending up with multiple instances again.

I can't add a private constructor however, since the generics break down then, requiring a public parameterless constructor to do new T() inside the Nested class.

If anyone has a nice solution to get around this, while keeping generics, please comment and let me know. Personally I feel safer using the non-generics solution for now, since it locks down new() instantiation of the Singleton.

As usual, the project is available again to look at for further detail.

Some additional information on the Singleton pattern:

 
Comments: 19
 
  • Hi David,

    I normally use the first approach. First reason is that I haven't had time to find a good fix for the generic version and having a public parameterless constructor is not a Singleton.

    Next, I rarely need to use a Singleton myself so I often cut to the chase and just use the nested class approach without generics.

    The only place I see the singleton used a lot is for data repository (see Martin Fowler Enterprise Patterns for this one) but since they are generated by an ORM I don't have to bother with that.

    So for me, Solution #1.

    Cheers

     
     
  • Hi Maxim, yeah, exactly the same thoughts here. I rarely use a singleton as well, and when I do, it's with Nested approach as well :)

     
     
  • We use a generic helper class that is based on the nested approach, it uses reflection to access the private ctor.

    public class Singleton where T : class
    {
    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }
    public static readonly T Instance = TypeHelper.InvokeParameterlessConstructor();
    }
    public static class TypeHelper
    {
    public static T InvokeParameterlessConstructor() where T : class
    {
    return typeof(T).InvokeMember
    (
    typeof(T).Name,
    BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
    null, null, null
    )
    as T;
    }
    }

     
     
  • ExNihilo

    One way to make the generics work is to use reflection to instantiate the class. That way you don't need the public constructor, but do pay the reflection price. But given that Singletons are..instantiated only once, I think its not such a big problem.
    Here's a nice example:
    http://www.wijix.com/post/2008/04/Generic-C-Singleton-goodness.aspx

    Though the Instance property needs to be changed, as it uses the C# 3.0 syntax. Other than that, its pretty awesome.

     
     
  • Hi Andrew,

    Thanks for the comment! Great idea there :)

    It seems you have implemented it as the following version: 'Fourth version - not quite as lazy, but thread-safe without using locks', from the article I linked (http://www.yoda.arachsys.com/csharp/singleton.html)

    I took a moment to try and apply it to this version as well: 'Fifth version - fully lazy instantiation', and am happy with the result, thanks for inspiration!

    It'll be included in the future solutions for this series, and I'll post an update tomorrow with credits. (Too tired now :p)

     
     
  • Hi ExNihilo,

    Seems you had the same idea as Andrew, just started approving comments in the moderation queue ;)

    Nice implementation as well. I'll be settling for the following right now, and will create another post on it to start a discussion about possible drawbacks of it.

    (Code will look crappy in comments, sorry, tommorow's blog post will make it look better :p)

    public class Singleton< T > where T : class
    {
    protected Singleton() { }

    public static T Instance
    {
    get { return Nested.Singleton; }
    }

    private sealed class Nested
    {
    private static readonly T _instance = typeof(T).InvokeMember(typeof(T).Name,
    BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic,
    null,
    null,
    null) as T;

    internal static T Singleton
    {
    get { return _instance; }
    }
    }
    }

     
     
  • J

    For some unknown reason I was under the impression that using static get:ers would automatically make your code thread-safe. This would be taken care of by the CLR.

    However, after reading this post I see that this is not the case :)

    Anyone know where I got that from? Or if it's a misunderstanding of some sort?

     
     
  • Hi J,

    Can you post a piece of your Singleton code to illustrate this please?

     
     
  • From one of my coworker:

    public static class TypeHelper
    {
    public static T InvokeParameterlessConstructor() where T : class
    {
    return typeof(T).InvokeMember(typeof(T).Name, BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, null, null) as T;
    }
    }

    This is used to invoke the constructor even if the constructor is private.

    However, we must make sure that the class will stay valid with this invoke so I would use it for local components but not with 3rd party.

    Cheers

     
     
  • Hi Maxim,

    Thanks for your input as well. Seems Reflection is indeed the way to go :)

    I updated the code and made a follow-up blog post on this Generic Singleton Pattern (dubbed like that by me right now :p)

    http://blog.cumps.be/design-patterns-generic-singleton-pattern/

    Thanks for your input guys!

     
     
  • Lol, the comment dealy has a funny effect.

    I work with Maxim at Orckestra

    I definitely based it on the yoda.arachsys page, after I completed it, I found a few similar implementations.

     
     
  • Too much spam if I don't turn on comment moderation, sorry ;) And I need to eat/go out as well, added with the different timezones (most readers are from the US apparently) it can take a while to show up :p

     
     
  • Ah, by the way, I also removed BindingFlags.Public, since the constructor should always be private ;)

    If you by mistake are sloppy and don't add a private one (default public) or add a public one, the code will crash at runtime, giving you a chance to fix it :)

     
     
  • AndrewSeven

    BindingFlags.Public

    Nice catch :)

     
     
  • I'd encourage you to read this if you think singleton is actually useful in OO: http://steve.yegge.googlepages.com/singleton-considered-stupid

     
     
  • It exists, that's about the only thing I'd use it for ;) I kinda went through the same story as the one you linked.

    Long ago, when I was young :p, I used the Singleton in a project, and after that I didn't touch it anymore for years, until this article.

    As with most of good programming, you tend to "feel" things. And Singleton usually never shows up in my feelings when architecting something.

     
     
  • [quote]As you can see, the actual instance is held inside a private sealed nested class, which is inside the GraphicsCard class. When the Instance property is called for the first time, it will instantiate a GraphicsCard in a thread-safe way, thanks to the Nested class, and upon subsequent requests, the same instance will be returned.[/quote]

    Can you explain why working with an inner class makes it threadsafe?

    I think when 2 threads try to access the "get" of the enclosing class they both are redirected to the inner class where they could access the if loop at the same time again.

    Probably I am missing some basic functionality about how inner classes work but atm I would go for the adding the synchronized on top in the method signature.

     
     
  • Hi Tim,

    There's a good explanation about this on: http://www.yoda.arachsys.com/csharp/singleton.html

    Check version 4 and 5

    Nr 4 explains how the static way of working works, while nr 5 is just the next step after having that knowledge and making it lazy.

     
     
  • Mmm, I tried this solution in Silverlight 3 and it always threw an exception. (Exception in 'xxx' class constructor.)
    This with just an empty class with a private parameterless constructor.

    Is InvokeMember limited in Silverlight 3?

    Greetings

     
     
  • Leave a reply
    Items marked with * are required. (Name, Email, Comment)
    Comment is missing some required fields.
     
     
     
    To make sure you are not a computer, please type in the characters you see.