测试懒汉式 单例模式(如何防止反射漏洞)
public class Client2 {
public static void main(String[] args) throws Exception {
//通过反射方式直接调用私有构造器
Class<LazySingletonVSSyn> clazz = (Class<LazySingletonVSSyn>) Class.forName("singleton.LazySingletonVSSyn");
Constructor<LazySingletonVSSyn> c = clazz.getDeclaredConstructor();
c.setAccessible(true);
LazySingletonVSSyn ls3 = c.newInstance();
LazySingletonVSSyn ls4 = c.newInstance();
System.out.println(ls3);
System.out.println(ls4);
}
}
public class LazySingletonVSSyn {
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;
}
}