Published: 17 Sep 2008
By: Granville Barnett
Download Sample Code

In this part of the design patterns series we will look at the singleton pattern.

Contents [hide]

Introduction

The singleton pattern revolves around the mantra of their only ever being one instance of a type that is publicly available. Almost instantly you may be thinking of the static modifier that is present in C# and several other popular languages. When you declare something as being static you are declaring data that is associated with the type rather than an instance of that type. As we will see in this article this is a perfectly sensible approach to take, yet it does have some caveats as we will indeed discuss.

Our journey in this part of the design patterns series however will start with a very primitive design and implementation of the singleton design pattern.

Design Patterns Series

  • Part 1 Learn how to design more robust and maintainable code by incorporating design patterns into your software projects.
  • Part 2 This part shows the observer design pattern.
  • Part 3 In this part you will learn about the factory pattern.
  • Part 4 This part of the design patterns covers the singleton pattern.
  • Part 5 In this part of the design patterns series we investigate the command pattern and its uses.
  • Part 6 In this part of the design patterns series we will look at the adapter pattern.
  • Part 7 In this part of the design patterns series we will take a look at the template pattern.
  • How is a singleton typically implemented?

    Normally a singleton type is publicly viewable within the context of its use yet its constructor is private. By making the constructor private only the type itself can instantiate the type. An instance of the type is usually created upon the invocation of a method whose sole purpose is to a) verify that an instance of the type is not already available; and b) if a) was true then instantiate an instance of the type. The constraint in a) will only ever be true once, if this property doesn’t hold then we don’t have a singleton. Generally the method that contains this logic is named something like GetInstance. The former convention is fairly popular across various platforms and it describes the intent of the method well. As we are using C# and with the knowledge that C# supports properties we will use a getter property called Instance which will contain a small amount of logic to verify the constraint mentioned previously.

    Now that we have described a little about the singleton we can at least push on and create a type that implements those ideas in which we have discussed. For our example we will base it upon the prime minister (or president depending upon your location) of a country, of which there is only ever one at any one time. The following Figure shows the UML for our example.

    Figure 1: Prime minister singleton

    Prime minister singleton

    As you can tell the singleton pattern is very simple, thus far it is conceptually the most trivial we have encountered. The Instance property as mentioned prior will enforce our singleton constraint. The constraint being that only one instance of type PrimeMinister is available for all those who are interested.

    Before we proceed we should at least reiterate over a few key details about the static modifier. We already noted in the introduction that static members and methods are associated with the type rather than an instance of the type. Moreover if you come across a class that is annotated with the static modifier then you cannot create an instance of it.

    The following listing shows the implementation of our singleton PrimeMinister type.

    The code described in the previous listing can be used as follows.

    There is glaring issue with our singleton implementation. The issue is directly connected with the constraint listed in a). Don’t worry if the problem isn’t apparent to you at the present time, we will cover this in due course.

    A pretty interesting property of the singleton design pattern is that the instance of the PrimeMinister type won’t be instantiated until someone actually wants an instance of the PrimeMinister type. We can look at this as being good and bad, for example if we have clients that will be requesting an instance of the PrimeMinister type all the time then this approach is most likely going to be marginally slower. A solution may just be to use the static modifier and scrap the lazy like instantiation of our type altogether. More on this later.

    The static modifier

    To start this section we will present a slightly different approach for a PrimeMinister singleton.

    The major difference is one of context. The design that we originally implemented would instantiate an instance of PrimeMinister only if someone actually referenced the Instance property. In the latter however, the instance of PrimeMinister is created irrespective of the fact if anyone actually uses it. The difference between the two then revolves around the time of instantiation. We can think of the version presented in this section as instantiating the PrimeMinister type at load time, rather than runtime. This description isn’t entirely correct, however for the time being though it may help the reader to differentiate between the two. We will discuss about the technicalities imposed upon us by the use of the static modifier later.

    Note:

    I feel almost compelled to mention that we could have instantiated the PrimeMinister object within a static constructor. Keep this in mind as the provision of a static constructor holds some significance later on.

    Issues with our first design

    The problem with our first design is that it’s not thread safe, and as a result we can’t guarantee that only one instance of PrimeMinister will be around. Because of this issue our first design isn’t a very good singleton, in fact you should never use it. In contrast the version of our singleton that instantiated the instance of PrimeMinister statically is thread safe.

    In the second version we rely on the just-in-time (JIT) compiler to instantiate the PrimeMinister singleton instance before it is referenced. We will provide a little more discussion about how the JIT guarantees this behavior later on.

    How can we make our original design thread safe? The original design can be made thread safe by using a single lock that encapsulates a) and b).

    beforefieldinit

    While writing this article I wanted to look at the behavior of the beforefieldinit intermediate language (IL) modifier a little more. This modifier is added to any class that has a static field. Incidentally this modifier is not present if you provide a static constructor.

    After searching around to find out the behavior of this modifier I found the MSDN documentation pretty hazy. I stumbled across a pretty interesting performance article on MSDN [1] which opened with the following paragraph:

    When a type declares an explicit static constructor, the just-in-time (JIT) compiler adds a check to each of the type's static methods and instance constructors to ensure that the static constructor was previously called. Static initialization is triggered when any static member is accessed or when an instance of the type is created. However, static initialization is not triggered if you declare a variable of the type but do not use it, which can be important if the initialization changes global state.”

    The following paragraph from the referenced article describes the approach that we currently use:

    “When all static data is initialized inline and an explicit static constructor is not declared, Microsoft intermediate language (MSIL) compilers add the beforefieldinit flag and an implicit static constructor, which initializes the static data, to the MSIL type definition. When the JIT compiler encounters the beforefieldinit flag, in most cases the static constructor checks are not added. Static initialization is guaranteed to occur at some time before any of the static fields are accessed but not before a static method or instance constructor is invoked. Note that static initialization can occur at any time after a variable of the type is declared.”

    The key point here is “Static initialization is guaranteed to occur at some time before any of the static fields are accessed but not before a static method or instance constructor is invoked” As it turns out then the design that we presented before the one that used a lock seems to be pretty efficient as the JIT won’t check that the static constructor was previously called, but it will guarantee that by the first time we reference the static field (which is in the return in Instance) that it will be initialized. Having said this, and after consultation with Jon Skeet [2] I have opted to go with the use of a static constructor so that the PrimeMinister class is never initialized unnecessarily. The following listing is our final version of the PrimeMinister singleton.

    Summary

    In this article we have looked at several ways to implement a singleton ranging from the unsuitable (our first design) to the more suitable. As we have seen the singleton design pattern is trivial to understand however the key to enforcing a singleton is by making the implementation thread safe. For the latter we looked at three different versions, two of which used the static C# modifier, the other using a lock. In the first implementation using the static modifier we relied on the JIT to initialize our singleton object, in the second we enforced that the singleton type instance would not be instantiated unnecessarily.

    As you can tell from this article there are a number of ways to create a thread safe singleton type and we have by no means exhausted all these approaches. However, we have covered several very common approaches to the implementation of a thread safe singleton. For further ideas on thread safe singleton approaches you can check out the ones that Jon presents [3], and Scott Galloway also presents another interesting approach [4].

    Acknowledgements

    I’d like to thank Jon Skeet [5] who cleared up some of the issues I had relating to the beforefieldinit modifier and its associated behavior.

    References

    [1] http://msdn.microsoft.com/en-us/library/ms182275.aspx
    [2] http://www.yoda.arachsys.com/csharp/beforefieldinit.html
    [3] http://www.yoda.arachsys.com/csharp/singleton.html
    [4] http://www.mostlylucid.co.uk/archive/2008/04/30/grrr.poor-use-of-singletons-and-a-very-cool-generic-singleton.aspx
    [5] http://msmvps.com/blogs/jon_skeet/

    <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Granville Barnett

    Sorry, no bio is available

    This author has published 32 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Introduction to StructureMap
    Have you heard of StructureMap, generally know what it’s for, and want to know how to get started qu...
    DI Patterns: Constructor Injection
    In this article, an excerpt from the book "Dependency Injection in .NET", we will take a detailed lo...
    The Command Pattern
    In this article I will provide a quick refresher on what the command pattern is used for, how it wor...
    TypeMock’s Arrange-Act-Assert
    Brian Mains discusses how to implement the Arrange-Act-Assert pattern in TypeMock.
    Key Process Patterns
    This article, based on chapter 2 of Specification by Example, presents effective patterns for softwa...

    You might also be interested in the following related blog posts


    Learn design patterns from real projects: JBoss case study (Part 1). read more
    Designing a Windows 8 Metro style app starting from an existing Windows Phone app Design Case Study Part 1 read more
    Oredev Wrap-Up read more
    Introducing SharePoint 2010 Training at U2U read more
    The Underground at PDC read more
    12 ASP.NET MVC Best Practices read more
    Screencast Whats new in the Entity Data Model Designer in VS2010 read more
    What needed to be monitored to get better Governance read more
    SharePoint 2010 Workflow read more
    Formatting Text in RadControls for WinForms Q3 2009 read more
    Top
     
     
     

    Discussion


    Subject Author Date
    placeholder One small rectification Costin Trifan 10/21/2008 6:18 AM
    RE: One small rectification Granville Barnett 10/21/2008 7:06 AM
    placeholder RE: RE: One small rectification Sonu Kapoor 10/21/2008 8:26 AM

    Please login to rate or to leave a comment.