简体   繁体   中英

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?

any other advantage for following this pattern?

Since Singleton can have one instance only , you have to prevent second instance creation. 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 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 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 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

Original pattern was devised before C# and .net, see 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

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 . This is because:

You can't have instances of static classes. This alone goes against most of OOP principles and design patterns. 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 .

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()'). 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. 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.

Source: https://en.wikipedia.org/wiki/Singleton_pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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