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, name: String, default: T): ReadWriteProperty<Any?, T> = Preference(context, name, default)
}
/**
* Kotlin库提供了几个接口,我们自己的委托必须要实
* 现: ReadOnlyProperty 和 ReadWriteProperty 。具体取决于我们被委托的对
* 象是 val 还是 var 。
* 我们要做的第一件事就是创建一个类然后继承 ReadWriteProperty */
class NotNullSingleValueVar<T> : ReadWriteProperty<Any?, T> {
private var value: T? = null
//Getter函数 如果已经被初始化,则会返回一个值,否则会抛异常。
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: throw IllegalStateException("${property.name} not initialized")
}
//Setter函数 如果仍然是null,则赋值,否则会抛异常。
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = if (this.value == null) value else throw IllegalStateException("${property.name} not initialized")
}
}
/**
* 泛型preference委托
* 访问Shared Preferences
* **/
class Preference<T>(val context: Context, val name: String, val default: T) : ReadWriteProperty<Any?, T> {
val ref: SharedPreferences by lazy { context.getSharedPreferences("News", Context.MODE_PRIVATE) }
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return findPreferenceByName(name, default)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putPreference(name, value)
}
private fun findPreferenceByName(name: String, default: T): T = with(ref) {
val res: Any = when (default) {
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is String -> getString(name, default)
is Long -> getLong(name, default)
is Float -> getFloat(name, default)
else -> throw IllegalArgumentException("this type not support")
}
return res as T
}
private fun putPreference(name: String, value: T) = with(ref.edit()) {
when (value) {
is Int -> putInt(name, value)
is Boolean -> putBoolean(name, value)
is String -> putString(name, value)
is Long -> putLong(name, value)
is Float -> putFloat(name, value)
else -> throw IllegalArgumentException("this type not support")
}.apply()
}
}
在 application 里调用上面自定义的 DelegatesExt
class App : Application() {
companion object {
// 自定义委托实现单例,只能修改这个值一次.
var instance: App by DelegatesExt.notNullSingleValue<App>()
}
override fun onCreate() {
super.onCreate()
instance=this
}
}
参考 https://blog.csdn.net/Jeff_YaoJie/article/details/79229071