Re: What is the better approach to implement Singleton pattern?
Steve wrote:
In general the safest way to handle the singleton pattern is to
construct the object as a static variable and to hide the constructor
as you have described. Provide a static access method that simply
returns the static variable.
That works provided the variable is read-only. Static variables pointing to
mutable objects or that are reassignable are rife with risk.
Static methods are somewhat safer.
Sometime this doesn't work. Say if you have to delay the instantiation
of the object for some reason - something called lazy initialisation.
In this case you get into threading issues. These are addressed by the
'double locking' pattern. Although even that is contentious.
The double-checked locking pattern is broken, unless synchronized.
One big problem with singletons is dealing with multiple class
loaders. You're fine when dealing with a simple app. Once a web-server
such as Tomcat gets involved you start having to consider multiple
class loaders. It's not difficult to see the problem you'll get into
when you realise a singleton is really specific only to the class
loader that creates it.
Many people suggest avoiding non-constant static variables altogether.
Then you might consider using something like Spring to handle the
creation and 'glue' of you objects. Spring provides a sort of object
registry and can be configured to handle objects as singletons or not.
--
Lew