以下代码是单例模式的代码
a变量要为静态的,表示每个类独一份,不然是每个对象独一份,即使在空参构造方法中将a变为true,a仅仅在当前对象中为true,再new一个新的任然为false,会导致依然能成功创建两个对象
这是一个低级的错误,最后在if语句里面输出a修改后的状态才恍然大悟
public class LazyMan {
private boolean a =false;
private LazyMan(){
synchronized (LazyMan.class){
if(a==false){
a=true;
}else {
throw new RuntimeException("不要试图使用反射破坏异常");
}
}
//System.out.println(Thread.currentThread().getName()+" ok ");
}
private static LazyMan lazyMan;
public static LazyMan Instance(){
if(lazyMan==null){
synchronized (LazyMan.class){
if(lazyMan==null){
lazyMan=new LazyMan();
}
}
}
return lazyMan;
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
LazyMan instance = LazyMan.Instance();
Constructor declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyMan lazyMan = declaredConstructor.newInstance();
System.out.println(instance);
System.out.println(lazyMan);
}
}