设计模式:单例模式

单例模式:

保证一个类只有一个实例,并且提供一个全局访问点。

使用场景:

单例模式只允许创建一个对象,因此节省内存,加快对象访问速度,因此在对象需要被公用的情况下使用适合使用

单例优点:

  • 只有一个实例,节约内存
  • 只创建一次,加快访问速度。
  • 提供了对唯一实例的受控访问。
  • 避免对共享资源的多重占用。

缺点:

  • 单利模式中没有抽象层,因此单例类的扩展有很大的困难。
  • 单例类的职责过重,在一定程度上违背了“单一职责原则”。

单例模式的几种实现方式:

  • 饿汉模式:
    在类加载时就完成了初始化,所以类加载较慢,但获取对象的速度快
package headFirst.Singleton;

/**
 * @author [email protected]
 * @date 2019-07-21 00:04
 */
public class Hungry {
    private static Hungry instance = new Hungry();
     private Hungry (){
     }
     public static Hungry getInstance() {
     return instance;
     }
}

  • 懒汉模式(线程不安全)
    在用户第一次调用时初始化,线程不安全
/**
 * @author [email protected]
 * @date 2019-07-21 00:18
 */
public class Lazy {
      private static Lazy instance;  
      private Lazy (){
      }   
      public static Lazy getInstance() {  
      if (instance == null) {  
          instance = new Lazy ();  
      }  
      return instance;  
      }  
 
}
  • 懒汉模式(线程安全)
    加锁保证线程安全
/**
 * @author [email protected]
 * @date 2019-07-21 00:21
 */
public class LazySafe {
       private static LazySafe instance;
      private LazySafe (){
      }
      public static synchronized LazySafe getInstance() {
      if (instance == null) {
          instance = new LazySafe();
      }
      return instance;
      }
}
  • (懒汉)双重检查模式
/**
 * @author [email protected]
 * @date 2019-07-21 00:24
 */
public class DCL {
        private volatile static DCL instance;  
      private DCL (){
      }   
      public static DCL getInstance() {  
      if (instance== null) {  
          synchronized (DCL.class) {  
          if (instance== null) {  
              instance= new DCL();  
          }  
         }  
     }  
     return instance;  
     }
}
  • (懒汉)静态内部类单例模式
    第一次加载Singleton类时并不会初始化sInstance,只有第一次调用getInstance方法时虚拟机加载SingletonHolder 并初始化sInstance
/**
 * @author [email protected]
 * @date 2019-07-21 00:26
 */
public class Singleton {
        private Singleton(){
    }
      public static Singleton getInstance(){  
        return SingletonHolder.sInstance;  
    }  
    private static class SingletonHolder {  
        private static final Singleton sInstance = new Singleton();  
    }
}
  • 枚举
    线程安全,简单,但是可读性不强,建议加注释
/**
 * @author [email protected]
 * @date 2019-07-21 00:28
 */
public enum SingletonEnum {
    INSTANCE;
}

你可能感兴趣的:(设计模式:单例模式)