单例模式通过反序列化后就不再是单例了

测试 单例通过反序列化出来就不再是单例,反序列化时会反射创建一个新的对象出来

public class SerializableSingle {
	public static void main(String[] args) throws Exception {
		ObjectOutputStream obc = new ObjectOutputStream(new FileOutputStream(new File("d:/single.txt")));
		obc.writeObject(Single003.getInstance());
		
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("d:/single.txt")));
		Single003 readObject = (Single003)ois.readObject();
		System.out.println(readObject == Single003.getInstance());//false
		
	}
}

  

解决就是在单例中定义readResolve()方法

猜你喜欢

转载自www.cnblogs.com/wgDream/p/12039014.html