简体   繁体   English

c#Singleton模式与静态属性

[英]c# Singleton Pattern vs Static Property

When I tried to use 2 different versions of the same class , they act actually the same. 当我尝试使用同一类的2个不同版本时,它们的行为实际上是相同的。

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 ? 单例和静态属性之间的区别在于2例,它是关于初始化时间的? 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 它们都是非静态的,唯一的区别是,第一个在Instance属性中初始化,第二个直接初始化

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. Singleton类的实例将在Singleton.Instance方法第一次请求时创建。

The instance of Singleton2 will be created on initialization of its type which can be caused by several mechanisms. Singleton2的实例将在其类型的初始化时创建,这可能由多种机制引起。 It will certainly be created before accessing any property or method on the Singleton2 class 它肯定会在访问Singleton2类上的任何属性或方法之前创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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