美文网首页
单例模式 singleton

单例模式 singleton

作者: MisAutumn | 来源:发表于2020-03-10 00:11 被阅读0次
    1. 饿汉模式,类加载到内存后就实例化一个类
      pros:JVM线程安全,JVM只load一个类到内存一次,static是class加载之后马上加载的
      cons:不用也实例化
    public class Manager {
      private static final Manager INSTANCE = new Manager();
      private Manager() {}
      // private static final Manager INSTANCE
      // static {
      //    INSTANCE = new Manager();
      //}
      
      public static Manager getInstance {
        return INSTANCE;
      }
    }
    
    1. 懒加载
      pros:需要时才加载
      cons:多线程访问有影响
      可以给方法加syncronized解决,但带来效率下降
    public class Manager {
      private static Manager INSTANCE;
      private Manager() {}
      
      public static Manager getInstance {
        if(INSTANCE == null) {
          Instance = new Manager();
        } 
        return INSTANCE;
      }
    }
    
    public class Manager01 {
        private static Manager01 INSTANCE;
        private Manager01() {}
    
        public static Manager01 getInstance() {
            if (INSTANCE == null) { // 判断没有一体化,相当于没加锁
                synchronized (Manager01.class) {
                    INSTANCE = new Manager01();
                }
            }
            return INSTANCE;
        }
    }
    

    没缺点了:双重检查

    public class Manager02 {
        private static Manager02 INSTANCE;
        private Manager02() {}
    
        public static Manager02 getInstance() {
            if (INSTANCE == null) { // 双重判断
                synchronized (Manager01.class) {
                    if (INSTANCE == null) {
                        INSTANCE = new Manager02();
                    }
                }
            }
            return INSTANCE;
        }
    }
    
    1. 静态内部类:最完美的
    public class Manager03 {
        private Manager03() {}
        private static class Manager03Holder { // 类加载时不会被初始化
            private final static Manager03 INSTANCE = new Manager03();
        }
        
        public Manager03 getInstance() {
            return Manager03Holder.INSTANCE; // 加载静态内部类
        }
    }
    

    相关文章

      网友评论

          本文标题:单例模式 singleton

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