简体   繁体   中英

c# Singleton Pattern vs Static Property

When I tried to use 2 different versions of the same class , they act actually the same.

I searched but can't find a satisfied answer for this question

What are the differences between Singleton and static property below 2 example, it is about initialization time ? and how can i observe differences ?

Edit : I don't ask about differences static class and singleton. Both of them non static, only difference is, first one initialized in Instance property, second one initialized directly

public sealed class Singleton
{
    private static Singleton instance;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

public sealed class Singleton2
{
    private static Singleton2 instance = new Singleton2();

    private Singleton2()
    {
    }

    public static Singleton2 Instance
    {
        get
        {
            return instance;
        }
    }
}

Your first singleton implementation isn't thread safe; if multiple threads try to create a singleton at the same time it's possible for two instances to end up being created. Your second implementation doesn't have that flaw.

Other than that, they're functionally the same.

The instance of the Singleton class will be created the first time it is requested by the Singleton.Instance method.

The instance of Singleton2 will be created on initialization of its type which can be caused by several mechanisms. It will certainly be created before accessing any property or method on the Singleton2 class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM