Java序列化机制对单例模式的影响及解决方法
序列化对单例模式和枚举类型安全的影响:
A.在枚举类型加入Java之前,往往采用以下的代码:
public class Orientation{
private static final Orientation HORIZONTAL=new Orientation(1);
private static final Orientation VERTICAL=new Orientation(2);
private Orientation(int v){ value=v; }//*注意单例模式中构造器为私有
private int value;
}
单例模式的私有构造器决定,除了Orientation.HORIZONTAL或Orientation.VERTICAL,不能创建对象.可以用==测试两个对象:
if(orientation==Orientation.HORIZONTAL) ...
但这种情况在实现序列化接口时会发生错误,当你序列化Orientation.HORIZONTAL或Orientation.VERTICAL,再反序列化出来时,会在内存中产生一个新的对象,导致以下比较错误:
if(saved==Orientation.HORIZONTAL) ...
即使是私有构造器,序列化机制依然能创建一个新的对象.
解决方案:增加readReslove方法,该方法会在反序列化时调用,且返回一个对象,这个对象就是readObject返回的对象:
public Object readObejct() throws ObjectStreamException{
if(value==1) return Orientation.HORIZONTAL;
if(value==2) return Orientation.VERTICAL;
return null;//这通常不发生
}