In practice, Singletons should be avoided where possible. Singletons make it very difficult to
mock your code, which makes it difficult to properly
unit test your classes. A better solutions is
inversion of control where you create your instance only once, and pass it forward to every method that needs it.
Singletons are often used for service locators. Service locators are
java classes that manage 'services' (in fact any java class you want), and can force a singleton behaviour of your class, without the need of a real singleton implementation of your class. But even service locators can be passed by
inversion of control...
And a little remark on the code Jason Fox provided. This code is not
thread safe: the thread may be stopped right after the (s == null) test, before the creation of the singleton. So, from the moment you use this code in a multithreaded environment, you are not sure of the singleton behaviour. Making this code thread safe will require you to make the method synchronized. But synchronized methods are slow, and should be avoided in 'normal' code. So an other solution is to instantiate the singleton at the declaration of the instance field. This has the drawback that you will have an instance of the class from the moment the class is accessed for the first time. But most of the time the first access to a singleton class would be a getInstance() call, so this isn't such a problem.
Regards,
Kris
[ June 28, 2004: Message edited by: Kris Philippaerts ]