方法一:
public class Singleton{
private Singleton(){};
//instance=null,懒汉模式;instance=new Singleton,饿汉模式
private volatile static Singleton instance=null;
public static getInstance(){
if(instance==null) //双重检测机制
{
synchronized(Singleton.class){
if(instance==null){ //双重检测机制
instance=new Singleton();
}
}
return instance;
}
}
}
静态内部类:
public class Singleton{
private static class LazyHolder{
private final static Singleton INSTANCE=new Singleton();
}
public static Singleton getInstance(){
return LazyHolder.INSTANCE;
}
}
INSTANCE初始化在调用getInstance方法,是的LazyHolder类加载时。无法防止利用反射重复构件对象
利用反射打破单例:
//获得构造器
Constructor con= Singleton.class.getDeclaredConstructor();
//设置可访问
con.setAccessible(true);
//构造对象
Singleton instance=(Singleton) con.newInstance();
枚举
public enum Singleton{
INSTANCE;
}