美文网首页
kotlin单例实现以及对应的java代码

kotlin单例实现以及对应的java代码

作者: 会思考的鸭子 | 来源:发表于2021-03-15 11:29 被阅读0次

    一、kotlin代码转换为java代码

    kotlin代码转换.png

    二、kotlin单例——object实现

    object SingleDemo{
        fun helloWold(){
            println("Hello World")
        }
    }
    

    编写了此kotlin代码之后,我们用上述的方式来转换成java代码:

    public final class SingleDemo {
       public static final SingleDemo INSTANCE;
    
       public final void helloWold() {
          String var1 = "Hello World";
          boolean var2 = false;
          System.out.println(var1);
       }
    
       private SingleDemo() {
       }
    
       static {
          SingleDemo var0 = new SingleDemo();
          INSTANCE = var0;
       }
    }
    

    可以看到,java代码的实现就是单例的饿汉式

    三、kotlin单例——懒汉式

    class Singleton private constructor() {
        companion object {
            private var instance: Singleton? = null
                get() {
                    if (field == null) {
                        field = Singleton()
                    }
                    return field
                }
    
            fun getSingletonInstance(): Singleton {
                return instance!!
            }
        }
    }
    

    转换为java代码(核心部分):

    public static final class Companion {
        private final Singleton getInstance()
        {
            if (Singleton.instance == null) {
                Singleton.instance = new Singleton ((DefaultConstructorMarker)null);
            }
    
            return Singleton.instance;
        }
    
        private final void setInstance(Singleton var1)
        {
            Singleton.instance = var1;
        }
    
        @NotNull
        public final Singleton getSingletonInstance()
        {
            Singleton var10000 =((Singleton.Companion)this).getInstance();
            if (var10000 == null) {
                Intrinsics.throwNpe();
            }
    
            return var10000;
        }
    
        private Companion()
        {
        }
    
        // $FF: synthetic method
        public Companion(DefaultConstructorMarker $constructor_marker)
        {
            this();
        }
    }
    

    四、kotlin单例——懒汉式安全实现

    class Singleton private constructor() {
        companion object {
            private var instance: Singleton? = null
                get() {
                    if (field == null) {
                        field = Singleton()
                    }
                    return field
                }
    
            @Synchronized
            fun getSingletonInstance(): Singleton {
                return instance!!
            }
        }
    }
    

    转换为java代码,其实就是对java版的getSingletonInstance()方法加上了synchronized关键字,这里就不贴出来了

    五、kotlin单例——双重检测锁

    class Singleton private constructor() {
        companion object {
            val instance : Singleton by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
                Singleton()
            }
        }
    }
    

    转换为java代码之后,发现主要是lazy()函数实现的双重检测所,进一步跟踪lazy得到如下源码:

    // 未初始化的变量 相当与 NULL
    internal object UNINITIALIZED_VALUE
    
    private class SynchronizedLazyImpl<out T>(initializer: () -> T, lock: Any? = null) : Lazy<T>, Serializable {
        private var initializer: (() -> T)? = initializer
        // 禁止指令重排序
        @Volatile private var _value: Any? = UNINITIALIZED_VALUE
        // 对象锁
        private val lock = lock ?: this
    
        override val value: T
            get() {
                val _v1 = _value
                // 不为空就返回
                if (_v1 !== UNINITIALIZED_VALUE) {
                    @Suppress("UNCHECKED_CAST")
                    return _v1 as T
                }
                // 加锁
                return synchronized(lock) {
                    val _v2 = _value
                     // 再次判空
                    if (_v2 !== UNINITIALIZED_VALUE) {
                        @Suppress("UNCHECKED_CAST") (_v2 as T)
                    } else {
                        val typedValue = initializer!!()
                        _value = typedValue
                        initializer = null
                        typedValue
                    }
                }
            }
            //... 省略一些方法
    }
    

    六、kotlin单例——静态内部类

    class Singleton private constructor() {
        companion object {
            val instance = Holder.holder
        }
    
        private object Holder{
            val holder = Singleton
        }
    }
    

    这里感觉跟kotlin的object饿汉式差别不大,都是在最开始实例化,只是中间嵌套了一层静态类,我们转换成java代码看一下:

    public final class Singleton {
       @NotNull
       private static final Singleton.Companion instance;
       public static final Singleton.Companion Companion = new Singleton.Companion((DefaultConstructorMarker)null);
    
       private Singleton() {
       }
    
       static {
          instance = Singleton.Holder.INSTANCE.getHolder();
       }
    
       @Metadata(
          mv = {1, 1, 16},
          bv = {1, 0, 3},
          k = 1,
          d1 = {"\u0000\u0014\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0003\bÂ\u0002\u0018\u00002\u00020\u0001B\u0007\b\u0002¢\u0006\u0002\u0010\u0002R\u0011\u0010\u0003\u001a\u00020\u0004¢\u0006\b\n\u0000\u001a\u0004\b\u0005\u0010\u0006¨\u0006\u0007"},
          d2 = {"Lcom/example/hellworld/Singleton$Holder;", "", "()V", "holder", "Lcom/example/hellworld/Singleton$Companion;", "getHolder", "()Lcom/example/hellworld/Singleton$Companion;", "HellWorld.app"}
       )
       private static final class Holder {
          @NotNull
          private static final Singleton.Companion holder;
          public static final Singleton.Holder INSTANCE;
    
          @NotNull
          public final Singleton.Companion getHolder() {
             return holder;
          }
    
          static {
             Singleton.Holder var0 = new Singleton.Holder();
             INSTANCE = var0;
             holder = Singleton.Companion;
          }
       }
    
       @Metadata(
          mv = {1, 1, 16},
          bv = {1, 0, 3},
          k = 1,
          d1 = {"\u0000\f\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0005\b\u0086\u0003\u0018\u00002\u00020\u0001B\u0007\b\u0002¢\u0006\u0002\u0010\u0002R\u0011\u0010\u0003\u001a\u00020\u0000¢\u0006\b\n\u0000\u001a\u0004\b\u0004\u0010\u0005¨\u0006\u0006"},
          d2 = {"Lcom/example/hellworld/Singleton$Companion;", "", "()V", "instance", "getInstance", "()Lcom/example/hellworld/Singleton$Companion;", "HellWorld.app"}
       )
       public static final class Companion {
          @NotNull
          public final Singleton.Companion getInstance() {
             return Singleton.instance;
          }
    
          private Companion() {
          }
    
          // $FF: synthetic method
          public Companion(DefaultConstructorMarker $constructor_marker) {
             this();
          }
       }
    }
    

    相关文章

      网友评论

          本文标题:kotlin单例实现以及对应的java代码

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