Kotlin 中的单例
以获取 Application 的单例来说明
在 java 中的单例
public class App extends Application {
private static App instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static App getInstance(){
return instance;
}
}
在 Kotlin 中的单例
第一种,仿照 java 中的写法
class App : Application() {
companion object {
private var instance: App? = null
fun instance() = instance
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
第二种,使用 Kotlin 自带的单例模式,使用 notNull 委托
companion object {
var instance: App by Delegates.notNull()
}
override fun onCreate() {
super.onCreate()
instance = this
}
第三种,Kotlin 库提供了几个接口,我们自己的委托必须要实现的几个接口,自定义单例模式,创建一个 DelegatesExt.kt 文件
object DelegatesExt {
//现在你可以创建一个对象,然后添加函数使用你的委托:
fun <T> notNullSingleValue(): ReadWriteProperty<Any?, T> = NotNullSingleValueVar()
fun <T> getPreference(context: Context,