饿汉式
public class HungrySingleton implements Serializable {
private final static HungrySingleton hungrySingleton;
static {
hungrySingleton=new HungrySingleton();
}
private HungrySingleton(){
}
public static HungrySingleton getInstance(){
return hungrySingleton;
}
}
序列化破坏单例模式
把instance序列化到一個文件中,再從文件中取出
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
HungrySingleton instance=HungrySingleton.getInstance();
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("singleton_file"));
oos.writeObject(instance);
File file=new File("singleton_file");
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
HungrySingleton newInstance= (HungrySingleton) ois.readObject();
System.out.println(instance);
System.out.println(newInstance);
System.out.println(instance==newInstance);
}
}
注意:两个对象不同!!!
解决
源码解析:
方法名通过反射获得