首先來寫一個單例的類:java
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 2spa
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 == Singleton