Java序列化与反序列化实现单例模式
package com.wkcto.sigleton.p4;
import java.io.*;
/**
* 序列化与反序列化的单例实现
*/
public class Test03 {
public static void main(String[] args) {
Singleton obj = Singleton.getInstance();
System.out.println( obj );
//对象序列化
try (
FileOutputStream fos = new FileOutputStream("singleton.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
){
oos.writeObject(obj); //单例对象的序列化
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//单例对象反序列化
try (
FileInputStream fis = new FileInputStream("singleton.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
){
obj = (Singleton) ois.readObject();
//直接打印obj对象的哈希码,与序列化时单例对象的哈希码不一样
System.out.println( obj );
//可以在反序列化时, 调用单例对象的readResolve()方法返回原来的单例对象
Singleton another = obj.readResolve();
System.out.println(another);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
package com.wkcto.sigleton.p4;
import java.io.Serializable;
/**
* 允许序列化的单例实现
*/
public class Singleton implements Serializable {
private static final long serialVersionUID = 7747765510030536000L;
private Singleton(){}
//定义静态内部类
private static class SingletonHandler{
private static Singleton obj = new Singleton();
}
public static Singleton getInstance() {
return SingletonHandler.obj;
}
//定义实例方法,返回静态内部类的静态对象
public Singleton readResolve(){
System.out.println("调用了单例 的实例方法readResolve");
return SingletonHandler.obj;
}
}