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 ?
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With