这两个单例 class 结构有什么区别?

What's the difference between these two singleton class structures?

我想知道这两个单例之间有什么区别类。我的教授向我们展示了最后一个,说它更灵活,性能更好。我也想知道为什么我的教授版本有一个私有构造函数,有人能解释一下为什么吗?

版本 1 - 我的版本(我相信是标准的):

public class Singleton {

    public static Singleton GetInstance() {
        return Singleton.instance ?? (Singleton.instance = new Singleton());
    }

版本 2 - 灵活且高性能:

public class Singleton {

    private Singleton() {} // Why this?

    private static class SingletonHolder() {
        public static readonly Singleton instance = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }
}

构造函数是私有的,以防止其他人显式实例化 class,从而严格执行单例模式。

至于嵌套的class,它使它变得懒惰并且thread-safe不需要锁。灵活性和 High-Performance 是这些主要好处之上的语义。 (我的意思是,如果你真的想要高性能,你应该真正地编写 C 或 C++ 代码)。 Jon Skeet 在这里解释了它。 https://csharpindepth.com/articles/Singleton(第五版)

在这个时代,版本 1 并不是完全标准的,大多数库都使用 System.Lazy<T> 包装器来管理懒惰,而没有嵌套 classes 的样板。

In c#, Private Constructor is a special instance constructor and it is used in a classes that contains only static members. If a class contains one or more private constructors and no public constructors, then the other classes are not allowed to create an instance for that particular class except nested classes.

构造函数是private,因为我们不希望任何外部class创建这个class的实例。

关于性能,在 version 1 你必须检查: 如果 class 的实例是空的然后创建一个实例,但是在 version 2 你有一个带有 readonly 字段的 static 构造函数,这意味着当 class 第一次调用时实例将被初始化,而下一次调用静态构造函数不再调用。

更多关于singleton模式的解释,你可以关注这个link