BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Design Patterns
.NET 1.1+

Singleton Design Pattern

The singleton pattern is a design pattern that is used to ensure that a class can only have one concurrent instance. Whenever additional objects of a singleton class are required, the previously created, single instance is provided.

What is the Singleton Pattern?

The singleton pattern is a Gang of Four design pattern. This is a creational pattern as it is used to control class instantiation. The pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance.

The singleton pattern is useful when a single, global point of access to a limited resource is required. It is more appropriate than creating a global variable as this may be copied, leading to multiple access points and the risk that the duplicates become out of step with the original.

An example of the use of a singleton class is a connector to a legacy data file that only supports a single reader at any time. In this case, creating multiple instances of the legacy data connector would simply cause all but the first to fail when reading from the file. By forcing a single, global instance to be used, only one underlying connection would ever be active.

Implementing the Singleton Pattern

Singleton Design Pattern UML

The UML class diagram above describes an implementation of the singleton pattern. In this diagram the only public interface element is the static "GetSingleton" method. This method returns the single instance held in the private "instance" variable. Usually an instance of the class is created only when first requested. This lazy initialisation ensures that if the class is never required, resources are not wasted.

The constructor for the class is marked as private. This prevents any external classes from creating new instances. The class is also sealed to prevent inheritance, which could lead to subclassing that breaks the singleton rules.

The following code shows the basic code of the design pattern implemented using C#:

public sealed class Singleton
{
    private static Singleton _instance;
    private static object _lockThis = new object();

    private Singleton() { }

    public static Singleton GetSingleton()
    {
        lock (_lockThis)
        {
            if (_instance == null) _instance = new Singleton();
        }

        return _instance;
    }
}

One important item to note in the above code is the "_lockThis" object and the use of locking within the "GetSingleton" method. As C# programs can be multithreaded, it is possible that two threads could request the singleton before the instance variable is initialised. In rare cases, these two threads may both create their own copies of the class, defeating the principle of the design pattern. By locking the dummy "_lockThis" variable whilst checking, and possibly creating, the instance variable, all other threads will be blocked for very brief period. This means that no two threads will ever be able to simultaneously create their own copies of the object.

Example Singleton

The singleton pattern is often used to hold the state of a program, particular in rich client applications. In the following example, a class is defined to hold the application's state. Two properties are required, one for the user's login details and one for the maximum size of some element that they can manipulate. To ensure that the state is only held in a single instance, the class uses the singleton pattern approach.

NB: For brevity the two properties are defined using the .NET 3.0 automatically implemented property syntax. For earlier versions of the .NET framework, these must be expanded.

public sealed class ApplicationState
{
    // Singleton Implementation
    private static ApplicationState _instance;
    private static object _lockThis = new object();

    private ApplicationState() { }

    public static ApplicationState GetState()
    {
        lock (_lockThis)
        {
            if (_instance == null) _instance = new ApplicationState();
        }

        return _instance;
    }

    // State Information
    public string LoginId { get; set; }
    public int MaxSize { get; set; }
}

Testing the Singleton

The above implementation of the singleton pattern can be easily tested. The following sample code creates two new variables and assigns the return value of the GetState method to each. They are then compared to check that they both contain the same values and a reference to the same object.

ApplicationState state = ApplicationState.GetState();
state.LoginId = "BlackWasp";
state.MaxSize = 1024;

ApplicationState state2 = ApplicationState.GetState();
Console.WriteLine(state2.LoginId);      // Outputs "BlackWasp"
Console.WriteLine(state2.MaxSize);      // Outputs "1024"
Console.WriteLine(state == state2);     // Outputs "True";
25 June 2008