posted 17 years ago
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