Question

In many of the Singleton examples, I have come across constructor having comment as "Exists only to defeat instantiation", can you please give me details and explain more about it.

Was it helpful?

Solution

It's common to create a private constructor when implementing the Singleton pattern so that the default constructor cannot be used to instantiate multiple Singleton objects.

See the example from Wikipedia's Singleton pattern article.

public class SingletonDemo {
    private static SingletonDemo instance = null;

    private SingletonDemo() {   }

    public static synchronized SingletonDemo getInstance() {
        if (instance == null) {
            instance = new SingletonDemo ();
        }
        return instance;
    }
}

By making a private constructor, you insure that the compiler can't make a default constructor with the same signature, which forces any client code to call the getInstance() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top