一個類實現了Serializable接口,咱們就能對它的對象序列化,即把對象轉換成字節數組寫到內存或磁盤。反序列化時,讀取內存(磁盤)中的字節數組,轉換成類的對象,這個對象是一個全新的對象,和原來對象的地址是不同的。這個過程調用了java
readResolve()方法。爲了不單例的破壞,咱們須要重寫這個方法。數組
public class TestSingleton { public static void main(String[] args) throws Exception { /** * 這樣打印出的TestSingleton對象地址一致, * 說明依然是單例對象 * 把readResolve方法註釋掉再來一遍看看呢? */ System.out.println(Singleton.getInstance()); System.out.println(Singleton.getInstance().deepCopy()); } } //單例 class Singleton implements Serializable { private static final long serialVersionUID = 1; private Singleton() { } private static class Holder { private static Singleton singleton = new Singleton(); } public static Singleton getInstance() { return Holder.singleton; } //重寫readResolve() private Object readResolve() throws ObjectStreamException { return getInstance(); } public Singleton deepCopy() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(Singleton.getInstance()); InputStream is = new ByteArrayInputStream(os.toByteArray()); ObjectInputStream ois = new ObjectInputStream(is); Singleton test = (Singleton) ois.readObject(); return test; } }