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 containing a method that creates an instance only if it does not already exist. Otherwise, it returns a reference to the instance previously created. In many object-oriented languages, it will be necessary to ensure that the constructor of the class is private, in order to ensure that the class can not be instantiated otherwise than by the controlled creation method.

Singleton should be implemented with caution in multi-threaded applications. If two threads simultaneously call the creation method while the single object does not exist yet, it is absolutely necessary to make sure that only one creates the object and that the other object will obtain a reference to this new object. The classic solution to this problem is to use mutual exclusion to indicate that the object is being instantiated.

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 appeared: Lazy<T>. As its name implies, it is lazy and therefore creates an instance only at the first call of the Value property. In addition, object creation can be thread-safe depending on the options. This really looks like a singleton.

Here is the implementation of a singleton with the class 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?Buy Me A Coffee💖 Sponsor on GitHub