序列化對單例模式的破壞
阿新 • • 發佈:2018-05-02
throw RR use als upload 序列化 ioe ati 文件操作
序列化對單例的破壞
首先來寫一個單例的類:
code 1
package com.hollis;
import java.io.Serializable;
/**
* Created by hollis on 16/2/5.
* 使用雙重校驗鎖方式實現單例
*/
public class Singleton implements Serializable{
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
接下來是一個測試類:
code 2
package com.hollis;
import java.io.*;
/**
* Created by hollis on 16/2/5.
*/
public class SerializableDemo1 {
//為了便於理解,忽略關閉流操作及刪除文件操作。真正編碼時千萬不要忘記
//Exception直接拋出
public static void main(String[] args) throws IOException, ClassNotFoundException {
//Write Obj to file
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("tempFile"));
oos.writeObject(Singleton.getSingleton());
//Read Obj from file
File file = new File("tempFile");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Singleton newInstance = (Singleton) ois.readObject();
//判斷是否是同一個對象
System.out.println(newInstance ==