Kotlin & Java 之单利模式

作者: 温暖的外星 | 来源:发表于2018-03-31 19:46 被阅读110次
    在 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 虚拟机已经帮我们完成这个操作了。

相关文章

  • Kotlin & Java 之单利模式

    第一种: 只适合单线程环境,懒汉模式 第二种: 第三种: 第四种: 关于第四种就是采用 volatile 关键字的...

  • kotlin 单利模式

    1. 懒汉式 java线程不安全 缺点是在多线程不能正常工作 线程安全 效率比较低 kotlin线程不安全 线程...

  • Kotlin学习之继承

    Kotlin学习之继承 @(Kotlin学习) Kotlin中的继承模式与Java中存在差异: Kotlin中所有...

  • Kotlin设计模式之命令模式

    简单介绍下用Kotlin写的命令模式,还有就是与之对比的Java版本。 Kotlin Java 输出

  • java 单利模式

    public class Singletion { private static class InnerSingl...

  • java单利模式

    不多BB,直接上个最好用的,线程安全的,使用静态内部类持有的静态对象

  • Java单利模式

  • java 单利模式

    大体思路:1 为了让内存中只有一份内存,就要防止外面进行new创建对象(new的本质是调用构造方法),因此,我们需...

  • Kotlin设计模式之策略模式

    简单介绍下用Kotlin写的策略模式,还有就是与Java版本的对比。 Kotlin Java 输出 实现策略模式时...

  • Kotlin单例的五种写法

    前言 单利模式是写代码过程中不可避免用到的,下面我总结一下单利常用的五中写法 加载类时创建单利 Java实现 Ko...

网友评论

本文标题:Kotlin & Java 之单利模式

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