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

Viewed 6467

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?

7 Answers

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 (i.e. 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

Related