I've seen a case made to make every class a factory for itself. If I write
all over my application, it will be hard to plug in a new implementation or extension of MyThing. If I write
I can easily change getInstance() to return SonOfMyThing or any new implementation that I might read from configuration.
Doing this on every class would seem to be overkill, but how confidently can we predict what classes we might like to make plug-ins later on? And what's the cost? One single-line method? [ February 27, 2007: Message edited by: Stan James ]
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Sometimes, when you write a class, you need to have control over how many instances of the class are made. For example, you might want to have it so that there is only one instance of the class, which is shared by all the users of the class. That's called the singleton pattern (link to a longer explanation above).
If you have one or more non-private constructors in your class, then the class does not have control over how many instances of the class are created - other classes can use "new ClassName" to make as many instances as they like. To get control over the creation of instances, you need to make all the constructors of the class private - which means that only methods in the class itself can access those constructors.
One common way in Java to implement a singleton class is to make all the constructors of the class private, and then to provide a static factory method like the getInstance() method you mentioned to get the single instance of the class. [ February 27, 2007: Message edited by: Jesper Young ]