代码之家  ›  专栏  ›  技术社区  ›  Matthew

这是一个有效的、懒惰的、线程安全的C单例实现吗?

  •  5
  • Matthew  · 技术社区  · 16 年前

    我实现了如下的单例模式:

    public sealed class MyClass {
    
        ...
    
        public static MyClass Instance {
            get { return SingletonHolder.instance; }
        }
    
        ...
    
        static class SingletonHolder {
            public static MyClass instance = new MyClass ();
        }
    }
    

    从搜索c singleton实现来看,这似乎不是在c中做事情的常见方法。我发现了一个类似的实现,但是singletonholder类不是静态的,并且包含一个显式(空)静态构造函数。

    这是实现singleton模式的有效、懒惰、线程安全的方法吗?或者是我遗漏了什么?

    1 回复  |  直到 11 年前
        1
  •  6
  •   Mark Byers    16 年前

    乔恩·斯凯特写了一篇 article 关于在c_中实现singleton模式。

    惰性实现是版本5:

    public sealed class Singleton
    {
        Singleton()
        {
        }
    
        public static Singleton Instance
        {
            get
            {
                return Nested.instance;
            }
        }
    
        class Nested
        {
            // Explicit static constructor to tell C# compiler
            // not to mark type as beforefieldinit
            static Nested()
            {
            }
    
            internal static readonly Singleton instance = new Singleton();
        }
    }
    

    请特别注意,即使构造函数为空,也必须显式声明它才能使其私有。