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.
A Singleton is used when you want to make sure that there is only one instance of your class present with a global point of access. The same instance is used to serve diferent requests. Please refer to the example below.
The Output - Creating Instance... Single@3ac748 Reusing Instance Single@3ac748
Notice that the constructor of class Single is private. Also it provides a public static method to create an object of class Single. Singletons can be used for ConcreteFactories which return a family of objects. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance i.e the static method used in our example needs to change. [ August 24, 2004: Message edited by: Nikhil Vasaikar ]
I've just been frustrated by a vendor package with a few static and singleton classes that were not designed for customization. The getInstance method on the class may burn you one day, too. Consider a nice utilitiy package you pick up somewhere with SingletonClass.getInstance(). After a while you decide you'd like to subclass SingletonClass with CustomSingleton and override a couple methods. But many places in your code you have calls to SingletonClass.getInstance(). Ouch.
If Singleton still seems to be your answer, maybe it should implement an interface so clients can be coded:
SingletonInterface x = ConfigurableFactory.getSingleton();