首發(fā)于公眾號: DSGtalk1989
我們直接使用最最契合的Kotlin
功能點(diǎn)叮趴,屬性代理來實(shí)現(xiàn)
首先我們按照文中所說轴或,先去實(shí)現(xiàn)ReadWriteProperty
接口拼余。
其中有一個(gè)細(xì)節(jié)點(diǎn)需要注意帕棉,我們在屬性委托這一章中沒有明確的指出ReadWriteProperty
兩個(gè)泛型參數(shù)的意義。
/**
* Base interface that can be used for implementing property
delegates of read-write properties.
*
* This is provided only for convenience; you don't have to extend this
interface
* as long as your property delegate has methods with the same
signatures.
*
* @param R the type of object which owns the delegated property.
* @param T the type of the property value.
*/
public interface ReadWriteProperty<in R, T>
有句話比較重要
This is provided only for convenience
可見只是為了方便衰抑,一旦你在內(nèi)部有了相同的方法就不一定要去實(shí)現(xiàn)這個(gè)接口象迎。。
OK停士,我們來看兩個(gè)泛型參數(shù)的解釋挖帘,R代表持有代理屬性的對象類型完丽,T代表代理屬性的類型恋技,我們再結(jié)合著兩個(gè)接口的方法來看就很清晰了。
/**
* Returns the value of the property for the given object.
* @param thisRef the object for which the value is requested.
* @param property the metadata for the property.
* @return the property value.
*/
public operator fun getValue(thisRef: R, property: KProperty<*>): T
/**
* Sets the value of the property for the given object.
* @param thisRef the object for which the value is requested.
* @param property the metadata for the property.
* @param value the value to set.
*/
public operator fun setValue(thisRef: R, property: KProperty<*>, value: T)
總結(jié)一下逻族,property
是我們無法改變的蜻底, 我們可以修改的就是R和T,那么為了使這個(gè)屬性代理面向的受眾更廣泛聘鳞,我們允許任何的對象去持有這個(gè)代理屬性薄辅,允許代理之后生成任何類型的對象。所以我們看到的代理屬性玩法一般是實(shí)現(xiàn)接口ReadWriteProperty<Any?,T>
抠璃。
有些同學(xué)會問站楚,前面的用Any?
不用R
,后面的用T
不用Any?
搏嗡,這里涉及到泛型的使用體會窿春,什么時(shí)候使用泛型什么時(shí)候使用Any?
或者java中的Object
拉一。其實(shí)就看我們最終是否需要去使用泛型。
也就說我們并不需要直接把R
拿來用旧乞,但是我們需要把T
拿來用蔚润,試想一下,我們T
改成Any?
尺栖,完全沒有問題嫡纠,但是代理的屬性瞬間就變成了Any?
,如果我們需要的是Stirng
或者是Int
延赌,就還需要做一層as
強(qiáng)轉(zhuǎn)除盏。
OK,此處不再做展開皮胡,相信大家對屬性代理的兩個(gè)方法應(yīng)該有了更深的見解痴颊。
好的,所以我們的SharePreferenceDelegate
變成了如下這樣屡贺。
class SharePreferenceDelegate<T>(private val key: String, private val defaultValue: T) : ReadWriteProperty<Any?, T>{
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
}
override fun setValue(thisRef: Any?, property: KProperty<*>, defaultValue: T) {
}
}
構(gòu)造函數(shù)的兩個(gè)參數(shù)還是很明顯的蠢棱,跟我們以前玩兒的SharePreference工具類差不多,都是傳入一個(gè)key
和默認(rèn)的defaultValue
甩栈。
至此屬性代理的一步完成了泻仙。也就是說接下去我們針對代理的屬性,它的每一次的賦值和每一次的取值都會去走代理的方法setValue
和getValue
按照我們以往的理解量没,在取值時(shí)玉转,我們需要從SP中將值取到,然后返回出去殴蹄。在賦值時(shí)究抓,我們需要將值存到SP中。
所以方法應(yīng)該是
@Suppress("UNCHECKED_CAST")
override operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
val prefs = FrameApplication.instance.getSharedPreferences(SpConst.DEFAULT_PKG, MODE_PRIVATE)
val result : Any = when (defaultValue){
is Long -> prefs.getLong(key, defaultValue)
is String -> prefs.getString(key, defaultValue)
is Int -> prefs.getInt(key, defaultValue)
is Boolean -> prefs.getBoolean(key, defaultValue)
is Float -> prefs.getFloat(key, defaultValue)
else -> throw IllegalArgumentException("Type Error, cannot be got!")
}
return result as T
}
override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
val prefs = FrameApplication.instance.getSharedPreferences(SpConst.DEFAULT_PKG, MODE_PRIVATE)
when (defaultValue){
is Long -> prefs.edit().putLong(key, defaultValue).apply()
is String -> prefs.edit().putString(key, defaultValue).apply()
is Int -> prefs.edit().putInt(key, defaultValue).apply()
is Boolean -> prefs.edit().putBoolean(key, defaultValue).apply()
is Float -> prefs.edit().putFloat(key, defaultValue).apply()
else -> throw IllegalArgumentException("Type Error, cannot be saved!")
}
}
這里有一些優(yōu)化的點(diǎn)袭灯,比如我們可以把方法進(jìn)行抽離刺下,顯得不那么臃腫;都用的prefs
是否需要每次都去初始化稽荧;什么時(shí)候用apply
什么時(shí)候用commit
橘茉。
所以最終我們優(yōu)化過后的SP
工具類是這樣的
class SharePreferenceDelegate<T>(
private val key: String,
private val defaultValue: T,
private val useCommit: Boolean = false
) : ReadWriteProperty<Any?, T> {
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return getSharePreferences(key, defaultValue)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putSharePreferences(key, value)
}
//延遲屬性,只會加載一次
private val prefs: SharedPreferences by lazy {
FrameApplication.instance.getSharedPreferences(
SpConst.DEFAULT_PKG,
Context.MODE_PRIVATE
)
}
@SuppressLint("ApplySharedPref")
private fun putSharePreferences(name: String, value: T) = with(prefs.edit()) {
val editor = when (value) {
is Long -> putLong(name, value)
is String -> putString(name, value)
is Int -> putInt(name, value)
is Boolean -> putBoolean(name, value)
is Float -> putFloat(name, value)
else -> throw IllegalArgumentException("Type Error, cannot be saved!")
}
if (useCommit) editor.commit() else editor.apply()
}
@Suppress("UNCHECKED_CAST")
private fun getSharePreferences(name: String, default: T): T = with(prefs) {
val res: Any = when (default) {
is Long -> getLong(name, default)
is String -> getString(name, default)
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is Float -> getFloat(name, default)
else -> throw IllegalArgumentException("Type Error, cannot be got!")
}
return res as T
}
}
當(dāng)我們需要使用SP
的時(shí)候姨丈,只需要像一般調(diào)用一樣取值和賦值就可以了畅卓。
var a by SharePreferenceDelegate("111", "222")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
a = "2"
}
輕松加愉快!
多嘮叨一句蟋恬,這里有個(gè)注意點(diǎn)翁潘,我們看到在prefs
的初始化中使用到了application的單例FrameApplication.instance
。來看下具體的代碼
class FrameApplication : Application() {
companion object {
var instance: FrameApplication by Delegates.notNull()
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
這里有個(gè)Delegates.notNull()
歼争,我們看下注釋拜马。
/**
* Returns a property delegate for a read/write property with a non-`null` value that is initialized not during
* object construction time but at a later time. Trying to read the property before the initial value has been
* assigned results in an exception.
*/
做一個(gè)屬性代理箱歧,代理的約束是必須先初始化,才能拿來使用一膨。有點(diǎn)像lateinit var
呀邢。從他的代碼中也很明顯可以看得出來。
private class NotNullVar<T : Any>() : ReadWriteProperty<Any?, T> {
private var value: T? = null
public override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: throw IllegalStateException("Property ${property.name} should be initialized before get.")
}
public override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
}
白話一點(diǎn)豹绪,我們可以直接把java中的代碼
private static FrameApplication instance;
轉(zhuǎn)化成
companion object {
var instance: FrameApplication by Delegates.notNull()
}
以上价淌。