zoukankan      html  css  js  c++  java
  • 单例模式(Singleton)Holder

    public class Singleton {
        /**
         * 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例
         * 没有绑定关系,而且只有被调用到才会装载,从而实现了延迟加载
         */
        private static class SingletonHolder{
            /**
             * 静态初始化器,由JVM来保证线程安全
             */
            private static Singleton instance = new Singleton();
        }
        /**
         * 私有化构造方法
         */
        private Singleton(){
        }
        public static  Singleton getInstance(){
            return SingletonHolder.instance;
        }
    }

    The solution of Bill Pugh

    University of Maryland Computer Science researcher Bill Pugh has written about the code issues underlying the Singleton pattern when implemented in Java.[10]Pugh's efforts on the "Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. The technique known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines.

    The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).

    public class Singleton {
            // Private constructor prevents instantiation from other classes
            private Singleton() { }
     
            /**
            * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
            * or the first access to SingletonHolder.INSTANCE, not before.
            */
            private static class SingletonHolder { 
                    public static final Singleton INSTANCE = new Singleton();
            }
            public static Singleton getInstance() {
                    return SingletonHolder.INSTANCE;
            }
    }

    Alternatively, the inner class SingletonHolder can be also substituted by implementing a Property which provides also access to the static final/read-only class members. Just like the lazy object in C#, whenever the Singleton.INSTANCE property is called, this singleton is instantiated for the very first time.

  • 相关阅读:
    Gecko SDK (XULRunner SDK)最新版
    北京联通机顶盒-中兴B860A破解
    litepdf简单的PDF操作库
    BZOJ1925 [SDOI2010]地精部落
    BZOJ 最大公约数 (通俗易懂&效率高&欧拉函数)
    Tarjan无向图的割点和桥(割边)全网详解&算法笔记&通俗易懂
    最近公共祖先综合算法笔记
    严格次小生成树[BJWC2010]
    NOIP2016 Day1 T2 天天爱跑步(树上差分,LCA)
    树上差分算法笔记
  • 原文地址:https://www.cnblogs.com/softidea/p/4273426.html
Copyright © 2011-2022 走看看