单例模式
DCL懒汉式
public class LazyMode {
private static volatile LazyMode LAZYMODE;
private LazyMode(){
}
public static LazyMode getInstance(){
if(LAZYMODE==null){
synchronized (LazyMode.class){
if(LAZYMODE==null){
LAZYMODE = new LazyMode();
}
}
}
return LAZYMODE;
}
public static void main(String[] args) {
LazyMode.getInstance();
}
}
以上这种模式并不能防止通过反射来创建对象。
如何解决呢?可以采用枚举
public enum SingleEnum {
SINGLE_ENUM;
public static SingleEnum getInstance(){
return SINGLE_ENUM;
}
public static void main(String[] args) {
SingleEnum.getInstance();
}
}