Posts Kotlin实现单例
Post
Cancel

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;
    }
}
1
2
//kotlin实现
object Singleton
1
2
3
4
5
6
7
8
9
10
11
12
13
//反编译上面的代码 Tools->Kotlin->Show Kotlin Bytecode
public final class Singleton {
   @NotNull
   public static final Singleton INSTANCE;

   private Singleton() {
   }

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

懒汉式

1
2
3
4
5
6
7
8
9
10
11
//java实现
public class Singleton {
    private static Singleton instance ;
    private Singleton(){}
    public static Singleton getInstance(){
        if(instance==null) {
            new Singleton();
        }
        return instance;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Singleton private constructor() {
  companion object {
    private var instance: Singleton? = null
      get() {
        if (field == null) {
          field = Singleton()
        }
        return field
      }
    fun get(): Singleton {
      return instance!!
    }
  }
}

双重校验锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//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()
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//参考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
      }
    }
  }
}

参考

This post is licensed under CC BY 4.0 by the author.

《Kotlin实战》第4章 类对象和接口

《Kotlin实战》第5章 Lambda编程

Comments powered by Disqus.