In a world before Java 1.5 (so no enum) and with my object being serialized, how can I enforce proper instance control? I’m talking about a class like this, where, as far as I can tell, I’m not sure that instance0 and instance1 will always be the only instances.
import java.io.Serializable;
public final class Thing implements Serializable {
private static final long serialVersionUID = 1L;
public static final Thing instance0 = new Thing();
public static final Thing instance1 = new Thing();
private Thing(){};
}
You should really check out Effective Java. The chapter on Singleton addresses this somewhat, and there is a chapter on the Typesafe Enum pattern that was definitely an influence on the way
enumwas implemented.The short answer is you have to implement
readResolve.