[SOLVED] Singleton Alternative – is it equivalent?

Issue

I know that the standard singleton pattern is as follows:

Original

public class Singleton1
{

    public static Singleton1 _Instance;
    public static Singleton1 Instance
    {
        get
        {
            if (_Instance == null)
            {
                _Instance = new Singleton1();
            }
            return _Instance;
        }
    }

    private Singleton1()
    {

    }
}

But it seems like this code is unnecessary. To me, you could accomplish the same thing with either of the following simple design patterns:

Version 2

public class Singleton2
{
    public static readonly Singleton2 Instance = new Singleton2();
    
    private Singleton2()
    {
    }
}

Version 3

public class Singleton3
{
    static Singleton3()
    {
    }
}

To me, it seems like version 2 is the superior method of doing this because it allows you to pass in parameters (or not) yet still have a finite number of instance. My application is fairly latency/performance sensitive – do any of these patterns have a performance gain?

It would seem that while it will longer to access each one the first time because the object is being created. Also, it would seem that the original one is ever so slightly slower because it must check to see whether its backing field is null every time something else accesses it.

Solution

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());

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

    private Singleton()
    {
    }
}

Fast, clean, thread-safe.

Answered By – Peter Kiss

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *