标签:
当第一次加载Singleton类时不会初始化sInstance,只有在第一次调用Singleton的getInstance方法时才会导致sInstance被初始化。因此第一次调用getInstance方法会导致
虚拟机加载SingletonHolder类,这种方法不仅能够确保线程安全,也能够保证单例对象的唯一性,同时也延迟的单例的实例化,所以这是推荐使用的单例模式方式
public class Singleton {
private Singleton(){};
public static Singleton getInstance(){
return SingletonHolder.sInstance;
}
/**
* 静态内部类
*/
private static class SingletonHolder{
private static final Singleton sInstance = new Singleton();
}
}
这个方法虽然好像也很不错,但是好像会出现什么双重检查锁定(DCL)失效。
public class MyImageLoader extends ImageLoader {
private static MyImageLoader instance;
public static MyImageLoader getInstance() {
if (instance == null) {
synchronized (MyImageLoader.class) {
if (instance == null) {
instance = new MyImageLoader();
}
}
}
return instance;
}
protected MyImageLoader() {
}
}
标签:
原文地址:http://www.cnblogs.com/zuiai/p/5809930.html