单例可以序列化,这里是如何做到这一点的代码:
import java.io.Serializable;
public class MySingleton implements Serializable {
private MySingleton(String name) {
this.name = name;
}
private static MySingleton mySingleton;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static MySingleton getInstance(String name) {
if(mySingleton == null) {
System.out.println("in if...");
mySingleton = new MySingleton(name);
}
return mySingleton;
}
}
这是“main”方法,它获取上面的 Singleton 类的实例,对其进行序列化和反序列化:
public static void main (String[] args) {
MySingleton m = MySingleton.getInstance("Akshay");
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D://temp.ser"));
oos.writeObject(m);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D://temp.ser"));
MySingleton m2 = (MySingleton) ois.readObject();
System.out.println(m2.getName());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
输出是: -
在如果...
阿克谢
谢谢。