This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
In the example you show I think it is indeed wrong to make the constructor protected instead of private.
By making it protected, the class can be instantiated in a subclass or in any other class in the same package (also classes in the same package that are not subclasses!). The class itself does not have complete control over instantiation this way, so this is not a good way to implement a Singleton. [ February 26, 2007: Message edited by: Jesper Young ]
Yes, you got the ideas correct. As described above, you probably need a private constructor to keep things safe.
The null check you showed is a risk in multi-threaded apps. You can synchronize the method to make it safer, or just create the instance when you declare it. With both of these changes ...
This makes the class a factory for its single instance. There are other ways to implement Singleton but this is the most common.
I'll attach the usual warning that Singleton invites a variety of problems into your code. It's global which is usually bad, impossible to extend because of the private constructor, difficult to replace because other classes are tightly bound to the class name, it really assures one instance per class loader instead of one instance per JVM, and more. Any time you're tempted to use one, look for alternatives. Sometimes Singleton is the right answer, but it is overused.
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
My understanding is that a single JVM can have more than one class loader. This pattern only guarantees one instance per class loader, so it's still possible to have more than one instance in the JVM of the singleton class. which is exactly what you don't want.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Jan 09, 2004
thanks Fred, I guess I need to do some independent research as well.
This makes the class a factory for its single instance
If Possible can you explain more on this sentence.
Thanks for your response guys
Joined: Jan 29, 2003
I call it a factory because it creates and provides access to the single instance. I usually add it's a "lower case factory" not one of the formally defined Something Factory patterns. I grew up calling generic creational utilities like that factories well before I saw GoF. Others may choose to call it something else.