DCLSingleton
缺点:可读性差
class Singleton {
private volatile static Singleton instance;
private Singleton(){}
public static Singleton getInstance() {
if ( instance == null ) {
synchronized (Singleton.class) {
if ( instance == null ) {
instance = new Singleton();
}
}
}
return instance;
}
}
(Singleton)Holder
缺点:能够被反射破坏
public class Singleton {
private static class SingletonHolder{
private static Singleton instance = new Singleton();
}
private Singleton(){
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
}
破坏方法
public class ReflectHungry {
public static void main(String[] args) {
try {
Class<?> clazz = HungrySingleton.class;
Constructor<?> constructor = clazz.getDeclaredConstructor(null);
constructor.setAccessible(true);
Object o1 = constructor.newInstance();
Object o2 = constructor.newInstance();
System.out.println(o1);
System.out.println(o2);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}