public class Client2 {
public static void main(String[] args) throws Exception {
//通过反序列化的方式构造多个对象
LazySingletonVSSyn ls1 = LazySingletonVSSyn.getInstance();
LazySingletonVSSyn ls2 = LazySingletonVSSyn.getInstance();
System.out.println(ls1 == ls2);//结果为true
FileOutputStream fos = new FileOutputStream("d:/a.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(ls1);
oos.close();
fos.close();
//反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/a.txt"));
LazySingletonVSSyn ls3 = (LazySingletonVSSyn) ois.readObject();
System.out.println(ls3);
}
}
public class LazySingletonVSSyn implements Serializable{
private static LazySingletonVSSyn ls ;
private LazySingletonVSSyn() {
if (ls!=null) {
throw new RuntimeException();
}
};//私有化构造器
//调用效率低
public static synchronized LazySingletonVSSyn getInstance() {
if (ls==null) {
ls = new LazySingletonVSSyn();
}
return ls;
}
//反序列化时,如果定义了readResolve()则直接返回方法指定的对象,而不需要单独在创建新对象
private Object readResolve() throws ObjectStreamException{
return ls;
}
}