Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

How can I implement the Singleton pattern in the Java programming language?

Answer: After further investigation, and consultation with a local expert, the c
ode previously on this page has been corrected as follows:
public class Singleton {
private static final Singleton INSTANCE =
new Singleton();
// Private constructor supresses
// default public constructor
private Singleton( ) {
}
public static Singleton getInstance( ) {
return INSTANCE;
}
}
If you want to make it serializable, then change the declaration to:
public class Singleton implements Serializable
and add this method:
private Object readResolve()
throws ObjectStreamException {
return INSTANCE;
}
The readResolve method serves to prevent the release of multiple instances upon
deserialization.

You might also like