Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a singleton class in java using public constructor

Do I have to use private constructor to make a class singleton ? Is there any other way than using private constructor ? Can't I make a class singleton using public constructor ?

like image 225
Manikanta Mani Avatar asked Sep 17 '15 10:09

Manikanta Mani


2 Answers

If your class has a public constructor, then anybody can create an instance of it at any time. So it's not a singleton any more. For a singleton, there can exist only one instance.

like image 176
volkanozkan Avatar answered Nov 15 '22 02:11

volkanozkan


The reason it has to be a private constructor is because you want to prevent people from using it freely to create more than one instance.

A public constructor is possible only if you are able to detect an instance already exist and forbid a another instance being created.

Is there no way other than using private constructor ? Can't we make a class singleton using public constructor ?

Yes, it is actually possible, for example:

class Singleton
{
    private static Singleton instance = null;
    public Singleton() throws Exception    //Singleton with public constructor
    {
       if(instance != null)
          throw new Exception("Instance already exist");      
       //Else, do whatever..such as creating an instance
    }
}
like image 26
user3437460 Avatar answered Nov 15 '22 03:11

user3437460