singleton与serializable

一个Singleton类如果可序列化,则除实现java.io.Serializable标记接口,还需定义
private Object readResolve() throws ObjectStreamException;


如果没有第二步则在反序列化的时候会重新生成一个对象.因而失去了Singleton.
原因在于:反序化也相当于构造方法生成一次对象.
   import java.io.*;
public class Thing implements Serializable
{
	private int id;
	private String name;
	private static Thing thing = new Thing();
	private Thing() {
	   this.id = -1;
	   this.name = "default";
	}
	public static Thing getInstance() {
	   return thing;
	}
	public String toString() {
	   return "Thing:[" + this.id + "," + this.name + "]";
	}
	public void setId(int id) {
	   this.id = id;
	}
	public void setName(String name) {
	   this.name = name;
	}
	private Object readResolve() throws ObjectStreamException {
	   return thing;
	}
	public static void main(String[] args) throws Exception{
	   Thing thing = Thing.getInstance();
	   System.out.println(thing);
	   thing.setName("new name");
	   System.out.println(thing);
	   Thing thing2 = Thing.getInstance();
       System.out.println(thing2);
       System.out.println(thing == thing2);
	   ObjectOutputStream objectOutputStream = new ObjectOutputStream(
		                       new FileOutputStream(
		                       new File("F:/aa.txt")));
	   objectOutputStream.writeObject(thing);
	   objectOutputStream.close();
	   ObjectInputStream objectInputStream = new ObjectInputStream(
		                                    new FileInputStream(
		                                    new File("F:/aa.txt")));
	   Thing thingSerializble = (Thing)objectInputStream.readObject();
       objectInputStream.close();
       System.out.println(thing == thingSerializble);
       System.out.println(thingSerializble);
	}
}


你可能感兴趣的:(java,F#)