跳转至

Kotlin实现单例

饿汉式

1
2
3
4
5
6
7
8
//java实现
public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return instance;
    }
}
//kotlin实现
object Singleton
//反编译上面的代码 Tools->Kotlin->Show Kotlin Bytecode
public final class Singleton {
   @NotNull
   public static final Singleton INSTANCE;

   private Singleton() {
   }

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

懒汉式

//java实现
public class Singleton {
    private static Singleton instance ;
    private Singleton(){}
    public static Singleton getInstance(){
        if(instance==null) {
            new Singleton();
        }
        return instance;
    }
}
class Singleton private constructor() {
  companion object {
    private var instance: Singleton? = null
      get() {
        if (field == null) {
          field = Singleton()
        }
        return field
      }
    fun get(): Singleton {
      return instance!!
    }
  }
}

双重校验锁

//Java实现
public class Singleton {
    private static Singleton instance ;
    private Singleton(){}
    public static Singleton getInstance(){
        if(instance==null) {
          synchronized (Singleton.class){
              if(instance==null){
                  instance = new Singleton();
              }
          }
        }
        return instance;
    }
}
1
2
3
4
5
6
7
8
//kotlin实现 不过这种没法传入参数
class Singleton private constructor() {
  companion object {
    val instance by lazy {
      Singleton()
    }
  }
}
//参考https://developer.android.com/codelabs/android-room-with-a-view-kotlin#7
//允许传入参数的DCL
class Singleton private constructor(a:Int) {
  companion object {
    @Volatile
    private var INSTANCE:Singleton? = null
    fun get(a:Int):Singleton{
      return INSTANCE?: synchronized(this){
        val instance = Singleton(a)
        INSTANCE = instance
        instance
      }
    }
  }
}

参考