设计模式的学习-单例模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/q1269463/article/details/63738222

最近正在阅读Android源码设计模式解析与实战来学习设计模式,写一下博客方便以后自己复习用。
1懒汉模式:
public class Singleton {
private static Singleton instance;
private Singleton(){}

 public static synchronized Singleton getInstance(){
     if(instance == null){
         instance = new Singleton();
     }
    return instance;
 }

}

懒汉模式只有使用时才会被实例化,一定程度上节约了资源。缺点在第一次加载时需要及时进行实例化,反应稍慢。
2:DLC方式实现单例模式
public class Singleton {
private static Singleton instance = null;
private Singleton(){};

  public static Singleton getInstance(){
      if(instance == null){
          synchronized(Singleton.class){
              if(instance == null){
                  instance = new Singleton();
              }
          }
      }
      return instance;
  }

}

DCL资源利用率,高效率高。但和懒汉模式一样第一次加载时反应稍慢。
3:静态内部类单例模式:

public class Singleton {
private Singleton(){};

public static Singleton getInstance(){
return SingletoHolder.instance;
}
private static class SingletoHolder{
private static final Singleton instance = new Singleton();
}
}
SingletoHolder是Singleton的内部类,在第一次加载Singleton类时并不会初始化instance,只有在调用 getInstance方法的时候才会去初始化
instance。这种模式不仅能保证线程安全和单例对象的唯一性,也能延迟单例的实例化。

猜你喜欢

转载自blog.csdn.net/q1269463/article/details/63738222