Creational Design Pattern: Singleton

For a long time now I’ve been telling myself I’ll blog a series on the various Design Patterns available to us for software architecture, and I’ll begin that today looking at the Singleton design pattern.

Whilst the examples used in this mini-series are provided in C#, they can be transposed and are applicable in every language.

Software Architecture Design Patterns are solutions for commonly occurring problems that all developers, or architects, face. The pattern itself is not a finished solution but rather a template or concept used in the creation of a solution. Generally speaking, there are multiple methods that can be used to implement design patterns, which may be dependent on language. However, the concept remains language agnostic.

Singleton

I’ll begin this mini-series in discussing the Singleton design pattern.

The singleton design pattern ensures that only a single instance of an object is held at any one given moment, that is shared with all users of an application instance.

Typically, a Singleton object will manage it’s own life cycle by holding a method to collect the instance of the object. The object itself will be held in memory and returned when requested. For example;

Singleton Class Diagram


public class MySingleton

{

    private static readonly Lazy<MySingleton> _instance = new Lazy<MySingleton>(() => new MySingleton());

    private MySingleton()

    {

        //...

    }

    public static MySingleton Instance

    {
        get
        {
            return _instance.Value;
        }

    }

    public bool SingletonMethod()

    {
        return true;
    }
}

//Access MySingleton

bool result = MySingleton.Instance.SingletonMethod() //True

System.Lazy<T> handles the initialization of the singleton, which incorporates its own locking mechanisms to ensure thread safety of the MySingleton object. This simple solution performs well and is thread safe.

An Alternate Approach

It’s always possible to impose the singleton concept on a class you don’t control, but you have to be careful as you aren’t altering the original class, thus it is possible to collect a new instance of the class. But consider the following;

You use a class from a third party provider which you want to use as a singleton, though it isn’t designed that way. You have two options here. One, is to create a Factory that returns the same instance of the class by caching at the factory level.

Alternatively, if you use a Dependency Injection or Service Location container, you can register the class with the container as a singleton instance. Most of the ones out there support this behavior (Including Mine), and if all of the calls for services are injected or located, you won’t have to worry as much about creating additional instances.

When Should You Use A Singleton?

This is a very difficult to answer question, as its entirely based on the situation, and can also depend on the wider architecture of a system.

However, some prime examples are for classes that aren’t required to be per-user, such as Logging, Configuration, Shared Resources or even Factories.

The Common Pitfall

The one thing that should remain on your mind when implementing a Singleton, is just that. The instance can only exist once, and is shared over every thread and every used.

If the state of the object is changed, it changes for every thread.

About Adam Riddick

When not Developing, Adam moonlights as a climbing frame for his two children. Adam Riddick was founded in 1987, in County Durham, England. Read More ...

02. December 2014 by Adam Riddick
Categories: Achitecture, Design & Practice | 2 comments