public class ImASingleton {
private static final ImASingleton INSTANCE = new ImASingleton();
private ImASingleton() {
}
public static ImASingleton getInstance() {
return INSTANCE;
}
}
And to be able to serialize this singleton, you had to do 3 things:
1. Implement the Serializable interface.
2. Mark the instance fields transient if you didn't want them to be serialized.
3. Define a readResolve() method to return the single instance. This is a hook method called in the deserialization process. If you don't provide this method, the default implementation will always create a new instance in stead of your unique instance!
public class ImASingleton implements Serializable {
private static final ImASingleton INSTANCE = new ImASingleton();
private final transient Object nonSerializableField;
private ImASingleton() {
}
public static ImASingleton getInstance() {
return INSTANCE;
}
private Object readResolve() {
return INSTANCE;
}
}
As of Java 1.5 the preferred way to create a singleton is simply by using an enum. This get's you the Serialization for free.
public enum MySingleton() {
INSTANCE;
}
No comments:
Post a Comment