设计模式:单例模式

2019-07-21  本文已影响0人  末日声箫

单例模式:

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

使用场景:

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

单例优点:

缺点:

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

package headFirst.Singleton;

/**
 * @author zhaokai008@ke.com
 * @date 2019-07-21 00:04
 */
public class Hungry {
    private static Hungry instance = new Hungry();
     private Hungry (){
     }
     public static Hungry getInstance() {
     return instance;
     }
}

/**
 * @author zhaokai008@ke.com
 * @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 zhaokai008@ke.com
 * @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 zhaokai008@ke.com
 * @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;  
     }
}
/**
 * @author zhaokai008@ke.com
 * @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 zhaokai008@ke.com
 * @date 2019-07-21 00:28
 */
public enum SingletonEnum {
    INSTANCE;
}
上一篇 下一篇

猜你喜欢

热点阅读