c# - 单例设计模式中私有(private)构造函数的需求是什么?

标签 c# design-patterns singleton singleton-methods

当我浏览下面的代码时,我找不到它在示例中使用私有(private)构造函数的原因?

public sealed class Singleton
    {
        private static Singleton instance = null;
        private Singleton()
        {
        }

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

                return instance;
            }
        }
    } 

...
  //Why shouldnt I use something like below.
  public class Singleton
  {
       private static Singleton instance = null;            

       static Singleton()
       {
       }

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

                return instance;
            }
        }
    } 

如果我创建了一个静态类而不是公共(public)类,我可以直接使用该类而不是创建实例。
当静态关键字持续到同一个工作时,在这里创建私有(private)构造函数有什么需要?

遵循这种模式还有其他优势吗?

最佳答案

单例类和静态类是不同的东西,你似乎把它混为一谈了。静态类只有静态方法和静态成员,因此不能有构造函数。静态方法是在类型上调用的,而不是实例上。

相比之下,单例类具有普通方法并使用实例调用。私有(private)构造函数用于防止创建该类的多个实例,并且通常由返回此唯一实例的私有(private)属性使用。

public class Singleton
{ 
    static Singleton s_myInstance = null;
    private Singleton()
    {
    }

    // Very simplistic implementation (not thread safe, not disposable, etc)
    public Singleton Instance 
    {
        get 
        { 
             if (s_myInstance == null) 
                   s_myInstance = new Singleton();
             return s_myInstance;
        }
     }
     // More ordinary members here. 
}

单例的优点是可以实现接口(interface)。此外,如果它们是有状态的(有很多成员),它们应该优于静态类,因为在静态类中有许多静态字段是非常丑陋的设计。

关于c# - 单例设计模式中私有(private)构造函数的需求是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36005348/

相关文章:

c# - 如何获取 google oauth 的访问 token ?

c# - Xamarin 表单切换按钮

c# - 设计模型以更轻松地在对象之间进行交互

java - java中Singleton的并发访问

c# - 如何将 ActivityIndi​​cator 添加到外壳弹出窗口

c# - keydown 卡住计时器 c#

c# - 将功能分为验证和实现?为什么?

java - 处理服务或 DAO 中的聚合

c# - 我可以将 Form 设为单例吗?

python - 跨模块单例