Java序列化與反序列化實(shí)現(xiàn)單例模式
package com.wkcto.sigleton.p4;
import java.io.*;
/**
* 序列化與反序列化的單例實(shí)現(xiàn)
*/
public class Test03 {
public static void main(String[] args) {
Singleton obj = Singleton.getInstance();
System.out.println( obj );
//對(duì)象序列化
try (
FileOutputStream fos = new FileOutputStream("singleton.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
){
oos.writeObject(obj); //單例對(duì)象的序列化
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//單例對(duì)象反序列化
try (
FileInputStream fis = new FileInputStream("singleton.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
){
obj = (Singleton) ois.readObject();
//直接打印obj對(duì)象的哈希碼,與序列化時(shí)單例對(duì)象的哈希碼不一樣
System.out.println( obj );
//可以在反序列化時(shí), 調(diào)用單例對(duì)象的readResolve()方法返回原來的單例對(duì)象
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;
/**
* 允許序列化的單例實(shí)現(xiàn)
*/
public class Singleton implements Serializable {
private static final long serialVersionUID = 7747765510030536000L;
private Singleton(){}
//定義靜態(tài)內(nèi)部類
private static class SingletonHandler{
private static Singleton obj = new Singleton();
}
public static Singleton getInstance() {
return SingletonHandler.obj;
}
//定義實(shí)例方法,返回靜態(tài)內(nèi)部類的靜態(tài)對(duì)象
public Singleton readResolve(){
System.out.println("調(diào)用了單例 的實(shí)例方法readResolve");
return SingletonHandler.obj;
}
}