栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java单例模式的实现的4种方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java单例模式的实现的4种方法

这里不做单例模式的概念解释
以下代码的实现参考《剑指offer》

法1 : 线程不安全版本
public final class Singletonl {

      private Singletonl() {
      }
      public int i;
 
      private static Singletonl instance = null;
 
      public static Singletonl Instance()
      {
          if(null == instance){
              instance = new Singletonl();
          }
          return instance;
      }
  }
 
 
法2 :线程安全版本
public final class Singletonl {

     private Singletonl() {
    }
     public int i;

     private static Singletonl instance = null;
 
      public static Singletonl Instance()
      {
          // 因为lock的成本较高,所以先判空
          if(null == instance){
              if(lock()){
                  instance = new Singletonl();
              }
          }
          return instance;
      }
 
  }
法3:静态构造版本
public final class Singletonl {
 
      private Singletonl() {
      }
      public int i;
 
      // 过早实例化(运行时),降低内存使用效率
      private static Singletonl instance = new Singletonl();
 
      public static Singletonl Instance()
      {
          return instance
      }
 
  }

法4:终极版本

public final class Singletonl {

    private Singletonl() {
    }
    public int i;

    // 按需实例化
    public static Singletonl Instance()
    {
        return Nested.instance;
    }

    static class Nested{
        private Nested(){}

        private static Singletonl instance = new Singletonl();
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/489849.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号