Java Reference
In-Depth Information
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance( );
tmp.demoMethod( );
}
}
Some commentators believe that a Singleton should also provide a public final clone()
method that just throws an exception, to avoid subclasses that “cheat” and clone() the
singleton. However, it is clear that a class with only a private constructor cannot be sub-
classed, so this paranoia does not appear to be necessary.
Variation
One variation is to make all methods static (as java.lang.Math does), but this works only if
methods do not need to share state. You also lose the scalability that is inherent in the
Singleton pattern: if you later need, say, two or three instances, you could easily change the
getInstance() method to give out references to one of several, but you can't do that if all
the methods are static.
See Also
The Collections class in java.util has methods singletonList() , singletonMap() ,
and singletonSet() , which give out an immutable List , Map , or Set , respectively, contain-
ing only the one object that is passed to the method. This does not, of course, convert the ob-
ject into a Singleton in the sense of preventing that object from being cloned or other in-
stances from being constructed, but it does qualify by providing a single access point that al-
ways returns the same instance.
Many frameworks including Spring and EJB3 ( Using Dependency Injection ) provide mech-
anisms for Singleton-style instantiation of plain classes.
Roll Your Own Exceptions
Problem
You'd like to use an application-specific exception class or two.
Search WWH ::




Custom Search