美文网首页
Java中单例模式的几种实现

Java中单例模式的几种实现

作者: 董成鹏 | 来源:发表于2018-10-11 20:40 被阅读0次
    1. 饿汉式单例
    public class Single{
      private static Single mInstance = new Single();
      private Single(){}
      public static Single getInstance(){
        return mInstance;
      }
    }
    

    优点是线程安全,缺点时没有办法实现懒加载。

    1. 懒汉式+同步方法单例
    public class Single{
      private static Signle mInstance;
      private Single(){}
      public static synchronized Single getInstance(){
        if(mInstance == null){
            mInstance = new Single();
        }
        return mInstance;
      }
    }
    

    优点是线程安全,懒加载
    缺点是效率不高

    1. volatile+Double Check方式
    public class Single{
      private volatile static Single mInstance;
      private Single(){}
      private static Single getInstance(){
        if(mInstance == null){
          synchronized(Single.class){
            if(mInstance == null){
              mInstance = new Single();
            }
          }
        }
        return mInstance;
      }
    }
    

    优点是线程安全,效率还可以

    1. Holder模式
    public class Single{
      private Single(){}
      private static class Holder{
        private static Single instance = new Single();
      }
      public static Single getInstance(){
        return Holder.instance;
      }
    }
    

    优点是线程安全,懒加载,效率高。

    1. 枚举方式
    public enum Single{
      //单例变量,也是枚举变量
      INSTANCE;
      public static getInstance(){
        return INSTANCE;
      }
    }
    

    优点,线程安全
    缺点,没有懒加载

    1. 枚举+Holder
    public class Single{
      private Single(){}
      //这个枚举类型的Holder主要是为了确保单例
      private enum EnumHolder{
        INSTANCE;
        //单例的枚举型中包含一个Single类型的变量
        private Single instance;
        EnumHolder(){
          //在构造函数中延时初始化
          this.instance = new Single();
        }
        //提供方法返回单例
        private Single getInstance(){
            return instance;
        }
      }
      //通过枚举类型返回单例实例
      public static Single getInstance(){
        return EnumHolder.INSTANCE.getInstance();
      }
    }
    

    相关文章

      网友评论

          本文标题:Java中单例模式的几种实现

          本文链接:https://www.haomeiwen.com/subject/giaswftx.html