演示了如何对单例模式的类进行序列化与反序列化
单例模式一般不会进行序列化与反序列化的,但是如果执行了序列化,再反序列化时得到对象将不再是单例模式的对象。
而readResolve()方法提供了将替换反序列化后的对象的机会。
1 package Pattern; 2 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.ObjectInputStream; 6 import java.io.ObjectOutputStream; 7 import java.io.ObjectStreamException; 8 import java.io.Serializable; 9 10 import org.junit.Assert; 11 12 /** 13 * @author LPX 14 * 15 */ 16 public class SerializableSingleton implements Serializable { 17 private SerializableSingleton(){ 18 System.out.println("construct"); 19 } 20 21 private static SerializableSingleton instance=null; 22 private static class SingletonHolder{ 23 public static SerializableSingleton holder=new SerializableSingleton(); 24 } 25 26 public static SerializableSingleton getInstance(){ 27 return SingletonHolder.holder; 28 } 29 30 /** 31 * 该方法是反序列化调用函数,用于对反序列化的数据时代替反序列化出的对象 32 * @return 33 * @throws ObjectStreamException 34 */ 35 private Object readResolve() throws ObjectStreamException{ 36 return this.getInstance(); 37 } 38 39 public static void main(String[] args) throws Exception{ 40 SerializableSingleton instance=SerializableSingleton.getInstance(); 41 42 //序列化 43 FileOutputStream fos=new FileOutputStream("data.db"); 44 ObjectOutputStream oos=new ObjectOutputStream(fos); 45 oos.writeObject(instance); 46 47 //反序列化 48 ObjectInputStream ois=new ObjectInputStream(new FileInputStream("data.db")); 49 SerializableSingleton tmp=(SerializableSingleton) ois.readObject(); 50 51 Assert.assertEquals("验证未通过", tmp, SerializableSingleton.getInstance()); 52 System.out.println("通过验证"); 53 } 54 }