Conclusions
Single-element enumeration types have become the best way to implement singleton singleton patterns
Common Singleton have two ways, the first:
public class Elvis {
//is defined as final, immutable public
static final Elvis INSTANCE = new Elvis ();
Private Elvis () {
} public
void Leavethebuilding () {
System.out.println ("Whoa baby, I ' outta here!");
}
//This code would normally appear outside the class!
public static void Main (string[] args) {
Elvis Elvis = elvis.instance;
Elvis.leavethebuilding ();
}
The second way:
public class Elvis {
private static final Elvis INSTANCE = new Elvis ();
Private Elvis () {
}
///defined as static method public
static Elvis getinstance () {return
INSTANCE;
}
public void leavethebuilding () {
System.out.println ("Whoa baby, I ' M outta here!");
}
This code would normally appear outside the class!
public static void Main (string[] args) {
Elvis Elvis = Elvis.getinstance ();
Elvis.leavethebuilding ();
}
let Singleton become serializable.
To create only one object for deserialization
public class Elvis {public
static final Elvis INSTANCE = new Elvis ();
Private Elvis () {
} public
void Leavethebuilding () {
System.out.println ("Whoa baby, I ' outta here!");
}
private Object Readresolve () {//Return the one true Elvis and let the
garbage collector
//Take care of the Elvis impersonator.
return INSTANCE;
}
This code would normally appear outside the class!
public static void Main (string[] args) {
Elvis Elvis = elvis.instance;
Elvis.leavethebuilding ();
}
using enumerations to implement a single case pattern
Provides a serialization mechanism for free, and absolutely prevents multiple instantiations
public enum Elvis {INSTANCE;
public void leavethebuilding () {System.out.println ("Whoa baby, I ' M outta here!");
}//This code would normally appear outside the class!
public static void Main (string[] args) {Elvis Elvis = elvis.instance;
Elvis.leavethebuilding (); }
}