Kotlin & Java 之单利模式

    在 Java 中单例模式的写法存在N种写法,这里只列举其中的几种。
  • 第一种: 只适合单线程环境,懒汉模式
    class UserProFile {

        private static UserProFile Instance = null;

        public UserProFile() {
        }

        public static UserProFile getInstance() {
            if (Instance == null) {
                Instance = new UserProFile();
            }
            return Instance;
        }
    }
  • 第二种:
    class UserProFile {

        private static UserProFile Instance = new UserProFile();

        public UserProFile() {
        }

        public static UserProFile getInstance() {
            return Instance;
        }
    }
  • 第三种:
    class UserProFile {

        private static UserProFile Instance = null;

        public UserProFile() {
        }

        public static UserProFile getInstance() {
            if (Instance == null) {
                synchronized (UserProFile.class) {
                    if (Instance == null) {
                        Instance = new UserProFile();
                    }
                }
            }
            return Instance;
        }
    }
  • 第四种: 关于第四种就是采用 volatile 关键字的 DoubleCheck 写法
    class UserProFile {

        private volatile static UserProFile Instance;

        public static UserProFile getInstance() {
            UserProFile inst = Instance;
            if (inst == null) {
                synchronized (UserProFile.class) {
                    inst = Instance;
                    if (inst == null) {
                        inst = new UserProFile();
                        Instance = inst;
                    }
                }
            }
            return inst;
        }
    }


---

- 这里讨论下 DoubleCheck 单利的写法

关于 DoubleCheck 这种单利写法, 在实际开发中是能够保护线程安全的, 比如第三种单例写法进行了双重判断, 在线程A进行访问的时候,线程B也请求过来了,这时就会出现对象错乱的情况,
那么在第四种单例模式中添加了 volatile 关键字之后, 就不会出现类似问题了, 因为 volatile 关键字可以保证对象在实例化以及对象的调用是有序的, 比如在线程A中在实例的时候线程B看到的实例
赋值以及构造方法其实是有序的调用, 先调用构造方法实例化完成之后才给 inst 赋值, 那也就是说 如果 inst 为 Null 一定是没有初始化完成, 如果 inst 不为 Null 那么一定初始化完成。


---
  • Kotlin 中 DoubleCheck 的写法
        class UserProFile {

            companion object {

                val instances by lazy(mode =  LazyThreadSafetyMode.SYNCHRONIZED){
                    UserProFile()
                }

                private @Volatile var mInstance : UserProFile? = null

                fun getInstance(): UserProFile {

                    if (null == mInstance){

                        synchronized(this){
                            if (null == mInstance){
                                mInstance = UserProFile()
                            }
                        }
                    }
                    return mInstance!!
                }
            }

        }
  • 在 kotlin 中通过 lazy 关键字来进行懒加载, 这里的 mode 为 SYNCHRONIZED
    。在 Kotlin 中 LazyThreadSafetyMode 一共有三个属性
       SYNCHRONIZED

       PUBLICATION

       NONE
  • 下面为 Kotlin 的源代码

      /**
       * Specifies how a [Lazy] instance synchronizes initialization among multiple threads.
       */
      public enum class LazyThreadSafetyMode {
    
          /**
           * Locks are used to ensure that only a single thread can initialize the [Lazy] instance.
           */
          SYNCHRONIZED,
    
          /**
           * Initializer function can be called several times on concurrent access to uninitialized [Lazy] instance value,
           * but only the first returned value will be used as the value of [Lazy] instance.
           */
          PUBLICATION,
    
          /**
           * No locks are used to synchronize an access to the [Lazy] instance value; if the instance is accessed from multiple threads, its behavior is undefined.
           *
           * This mode should not be used unless the [Lazy] instance is guaranteed never to be initialized from more than one thread.
           */
          NONE,
      }
    
  • 如果不采用 lazy 关键字实现单例模式,在 Java 与 Kotlin 中还有一种写法,代码如下

    class UserProFiles private constructor(){

      companion object {
          fun getInstance() = Holder.mInstance
      }
    
      private object Holder {
          val mInstance = UserProFiles()
      }
    

    }

  • Java 代码这里的写法几乎一致, 依然是采用静态内部类来做处理,这种写法就不用我们去考虑线程安全了,因为 Java 虚拟机已经帮我们完成这个操作了。

    原文作者:forYueji
    原文地址: https://www.jianshu.com/p/8419a5c8cf42
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞