静态内部类实现:私有静态内部类,getInstance
获取内部类的静态实例化变量
public class Configurator {
public static Configurator getInstance(){
return Holder.INSTANCE;
}
private static class Holder{
private static final Configurator INSTANCE = new Configurator();
}
}
双重检查加锁机制实现: 私有构造方法,私有实例,通过 getInstance
获取实例
public class Core {
private volatile static Core sInstance = null;
private Core(){}
public static Core getInstance() {
if (sInstance == null) {
synchronized (Core.class) {
if (sInstance == null) {
sInstance = new Core();
}
}
}
return sInstance;
}
}