Kotlin 单例模式与实现原理

前言

单例模式顾名思义线程中进程中创建类的唯一实例。

Object 实现饿汉式

Kotlin

object SingleDemo

就这么清爽,我们反编译下看下怎么实现的。

@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\u0002\bÆ\u0002\u0018\u00002\u00020\u0001B\u0007\b\u0002¢\u0006\u0002\u0010\u0002¨\u0006\u0003"},
   d2 = {"Lcom/ehi/pos/SingleDemo;", "", "()V", "pos_module_debug"}
)
public final class SingleDemo {
   public static final SingleDemo INSTANCE;

   private SingleDemo() {
   }

   static {
      SingleDemo var0 = new SingleDemo();
      INSTANCE = var0;
   }
}

提示:Kotlin每个类头都会有个Metadata注解进行标记类文件相关信息用于反射操作,以后单独写篇文章说。

懒汉式

Kotlin

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

反编译过来

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

线程安全懒汉式

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

加个注解搞定。反编译下:

@NotNull
public final synchronized SingleDemo get() {
   SingleDemo var10000 = ((SingleDemo.Companion)this).getInstance();
   if (var10000 == null) {
      Intrinsics.throwNpe();
   }
   return var10000;
}

对方法加锁.....

双重安全检查锁

Java

class SingleDemo {
    private static volatile SingleDemo INSTANCE = null;
    public static SingleDemo getInstance(){
        if (INSTANCE == null){
            synchronized (SingleDemo.class){
                if (INSTANCE == null){
                    INSTANCE = new SingleDemo();
                }
            }
        }
        return INSTANCE;
    }
}

Kotlin

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

相比与Java的双重检查锁方式是不是Kotlin太香了?不过看下原理其实是Kotlin帮我们进行处理了。

by lazy 原理

// 由此可见 若不指定Lazy的模式 默认是线程安全的懒加载实现。
public actual fun  lazy(initializer: () -> T): Lazy = SynchronizedLazyImpl(initializer)
// 懒加载3中可指定模式
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,
}
public actual fun  lazy(mode: LazyThreadSafetyMode, initializer: () -> T): Lazy =
    when (mode) {
        // 双重检查锁实现
        LazyThreadSafetyMode.SYNCHRONIZED -> SynchronizedLazyImpl(initializer)
        LazyThreadSafetyMode.PUBLICATION -> SafePublicationLazyImpl(initializer)
        LazyThreadSafetyMode.NONE -> UnsafeLazyImpl(initializer)
    }

SynchronizedLazyImpl

// 未初始化的变量 相当与 NULL
internal object UNINITIALIZED_VALUE

private class SynchronizedLazyImpl(initializer: () -> T, lock: Any? = null) : Lazy, 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
                }
            }
        }
        //... 省略一些方法
}

实现方式是不是一毛一样?哈哈.....

静态内部类

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

没啥好说的,很简单就创建出来了。反编译看下。

public final class SingleDemo {
   @NotNull
   private static final SingleDemo instance;
   public static final SingleDemo.Companion Companion = new SingleDemo.Companion((DefaultConstructorMarker)null);

   private SingleDemo() {
   }

   static {
      instance = SingleDemo.Holder.INSTANCE.getHolder();
   }

   public SingleDemo(DefaultConstructorMarker $constructor_marker) {
      this();
   }

// 静态内部类
 public static final class Holder {
      @NotNull
      private static final SingleDemo holder;
      public static final SingleDemo.Holder INSTANCE;
      @NotNull
      public final SingleDemo getHolder() {
         return holder;
      }
      private Holder() {
      }
      static {
         SingleDemo.Holder var0 = new SingleDemo.Holder();
         INSTANCE = var0;
         holder = new SingleDemo((DefaultConstructorMarker)null);
      }
   }
}

你可能感兴趣的:(Kotlin 单例模式与实现原理)