Singleton and Lazy<T>

 
 
  • Gérald Barré

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

The singleton is implemented by writing a class with a method that creates an instance only if one does not already exist, and otherwise returns a reference to the previously created instance. In many object-oriented languages, the class constructor must be private to ensure that the class cannot be instantiated except through this controlled creation method.

Singleton should be implemented with caution in multi-threaded applications. If two threads simultaneously call the creation method before the instance exists, you must ensure that only one thread creates the object and that the other receives a reference to the new instance. The classic solution is to use mutual exclusion to guard the instantiation.

Here is what the classic singleton implementation looks like:

C#
public class Singleton
{
    private static Singleton _instance;
    static readonly object instanceLock = new object();

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (instanceLock)
                {
                    if (_instance == null)
                        _instance = new Singleton();
                }
            }

            return _instance;
        }
    }
}

In .NET 4, a new class was introduced: Lazy<T>. As its name implies, it defers instance creation until the Value property is first accessed. Object creation can also be made thread-safe depending on the chosen options, making it a natural fit for implementing singletons.

Here is the implementation of a singleton using Lazy<T>:

C#
public sealed class Singleton
{
    private static Lazy<Singleton> lazy;

    private Singleton() { }

    static Singleton()
    {
        lazy = new Lazy<Singleton>(() => new Singleton(), true);
    }

    public static Singleton Instance
    {
        get
        {
            return lazy.Value;
        }
    }
}

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?