单例设计模式中私有构造函数的需要是什么?

Tom*_*ise 4 c# singleton design-patterns singleton-methods

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

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

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

                return instance;
            }
        }
    } 
Run Code Online (Sandbox Code Playgroud)

...

  //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;
            }
        }
    } 
Run Code Online (Sandbox Code Playgroud)

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

遵循这种模式还有其他好处吗?

PMF*_*PMF 5

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

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

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. 
}
Run Code Online (Sandbox Code Playgroud)

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


Has*_*riq 0

Singelton 为您提供实现接口的工具

Singelton pattren 具有广泛的用途,特别是您必须限制您的应用程序仅创建一个实例,就像在许多游戏中您只有一个实例一样