简体   繁体   English

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

[英]what is the need of private constructor in singleton design pattern?

when i go through the below code, i couldnt find the reason why it using private constructor in the sample? 当我通过下面的代码时,我找不到在示例中使用私有构造函数的原因?

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;
            }
        }
    } 

instead of public class if i created a static class, i can use the class directly rather than creating instance. 如果我创建了静态类,则可以使用公共类而不是创建实例来代替公共类。 what is the need of creating a private constructor here, when the static keyword persists to the same job? 当static关键字持续用于同一工作时,在这里创建私有构造函数有什么需要?

any other advantage for following this pattern? 遵循此模式还有其他优势吗?

Since Singleton can have one instance only , you have to prevent second instance creation. 由于Singleton只能有一个实例 ,因此必须防止创建第二个实例。 If you skip constructor declaration, eg 如果跳过构造函数声明,例如

  public class clsSingleTon {
  }

one can call a default constructor : 可以调用默认构造函数

  var one = new clsSingleTon();
  var two = new clsSingleTon(); // <- that's we try to ban

if you declare constructor being public , one can call it, so the only option is private one: 如果您声明构造函数为public ,则可以调用它,因此唯一的选择是private

  public class clsSingleTon {
     public static int intcounter;

     // No-one will call it
     private clsSingleTon() {
     } 
     ...
  }

however, it seems that you don't want any instances at all, so drop the constructor and declare the class as static : 但是,似乎根本不需要任何实例,因此删除构造函数并将类声明为static

  // Static class - no instances are allowed 
  public static class clsSingleTon {
    //TODO: turn it into property
    public static int intcounter;

    public static void Hit() {
    }

    //TODO: turn it into property, do not mimic Java
    public static int getTotalHits() {
      return intCouner;
    }
  }

  ...

  clsSingleTon.Hit();
  MessageBox.Show(clsSingleTon.getTotalHits().ToString());

A singleton class and a static class are different things, and it seems you're mixing that up. 单例类和静态类是不同的东西,看来您正在混淆。 A static class has only static methods and static members and therefore cannot have a constructor. 静态类仅具有静态方法和静态成员,因此不能具有构造函数。 Static methods are called on the type, not the instance. 静态方法是在类型而不是实例上调用的。

A singleton class, in contrast, has normal methods and is called using an instance. 相反,单例类具有常规方法,并使用实例进行调用。 The private constructor is there to prevent creating multiple instances of the class and usually used by a private property that returns this only instance. 私有构造函数在那里防止创建该类的多个实例,通常由返回该唯一实例的私有属性使用。

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. 
}

The advantage of singletons is that they can implement interfaces. 单例的优点是它们可以实现接口。 Also, they should be preferred over static classes if they are stateful (have many members), as having many static fields in a static class is quite ugly design. 此外,如果它们是有状态的(具有许多成员),则它们应优先于静态类,因为在静态类中具有许多静态字段是非常丑陋的设计。

Singelton provides you the facility to implement the interfaces Singelton为您提供了实现接口的工具

Singelton pattren has wide usage specialy where you have to limit your application to create only one instance just like in many games you have only one instance Singelton pattren具有广泛的用途,您必须限制应用程序仅创建一个实例,就像在许多游戏中只有一个实例一样

Original pattern was devised before C# and .net, see http://www.blackwasp.co.uk/gofpatterns.aspx 原始模式是在C#和.net之前设计的,请参见http://www.blackwasp.co.uk/gofpatterns.aspx

Canonical implementation was in c++, which doesn't have static classes, therefore you had to use private constructor trick in order to control class instantiation 规范实现是在C ++中实现的,它没有静态类,因此必须使用私有构造器技巧才能控制类的实例化

There is a private constructor so it can be called only within the class. 有一个私有的构造函数,因此只能在类中调用它。 Then you will have to define a static method which will 'lock' your class and instantiate it. 然后,您将必须定义一个静态方法来“锁定”您的类并将其实例化。

In an ideal OOP world, you should have no static classes . 在理想的OOP世界中,您应该没有静态类 This is because: 这是因为:

You can't have instances of static classes. 您不能有静态类的实例。 This alone goes against most of OOP principles and design patterns. 仅此一项就违反了大多数OOP原则和设计模式。 Just open a list of design patterns , go through them one by one, and ask yourself - can I do this without having an instance of a class? 只需打开一个设计模式列表,一个接一个地浏览它们,然后问自己- 我可以在没有类实例的情况下做到这一点吗? If the answer is no - you have an advantage on using a singleton pattern over a static class. 如果答案是否定的,那么与静态类相比,使用单例模式具有优势。


As for using a private constructor - read the answer by Dmitry Bychenko . 至于使用私有构造函数,请阅读Dmitry Bychenko答案

A private constructor is not solely tied to a singleton class. 私有构造函数并不仅限于单例类。 Even with a class that is meant to have multiple instances, using a public constructor results in a distributed memory allocation model (ie control of allocating memory is in the hands of any code that can call 'new()'). 即使对于打算具有多个实例的类,使用公共构造函数也会导致分布式内存分配模型(即,可以在任何可以调用“ new()”的代码的手中进行内存分配的控制)。 If, instead, you have a private constructor and a public (static) factory method, memory allocation can be centralized. 相反,如果您具有私有构造函数和公共(静态)工厂方法,则可以集中进行内存分配。 There are many cases where you use private constructors. 在许多情况下,您使用私有构造函数。

  1. You have a utility class which exposes only static util functions, for example a helper class to convert rest models to db models and vice versa, a class which has all String literals being used by your application. 您有一个仅公开静态util函数的实用程序类,例如,一个将其余模型转换为db模型,反之亦然的助手类,该类具有应用程序使用的所有String文字。 Since all the methods/fields are public static there is no meaning of an object of this class. 由于所有方法/字段都是公共静态的,因此没有此类的对象的含义。

  2. You want only one instance of a class not because you are trying to save memory, rather you want all components in your application to use same instance, for example db connection manager, an in-memory cache implementation, etc. 您只希望一个类的一个实例不是因为您试图节省内存,而是希望应用程序中的所有组件都使用同一实例,例如db连接管理器,内存中的缓存实现等。

Source: https://en.wikipedia.org/wiki/Singleton_pattern 资料来源: https : //en.wikipedia.org/wiki/Singleton_pattern

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

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