Kotlin之委托(代理)
一、介绍
设计模式中有个委托模式(即代理模式),比如想在国外买东西,我们并不需要自己跑到国外,只要告诉代购我们想要的东西,代购替我们购买即可。kotlin中的委托可以通过by关键字,但是这个类必须需实现接口。
二、委托类的普通实现
(1)创建一个接口
interface AddInterface {
fun add(a:Int,b:Int):Int
}
(2)实现接口
这个类即实现类,真正实现功能的地方
class AddImp:AddInterface {
override fun add(a: Int, b: Int): Int {
return a+b
}
}
(3)创建代理类
我们只需要向代理类传递一个具体的实现类实例,并在方法调用时,调用这个实例的方法
class RealAdd : AddInterface {
var imp:AddImp? = null
constructor(imp: AddImp){
this.imp = imp
}
override fun add(a: Int, b: Int): Int {
//调用实现类的方法
return imp?.add(a,b) ?: 0
}
}
三、kotlin的委托类实现
上面章节中实现的委托,还是有很多样板代码的,但是在kotlin这些样板代码都可以通过by关键字被简化。
例如RealAdd这个类可以简化成下面的代码
class RealAdd : AddInterface by AddImp()
我们将这个代码转成java代码看看是怎么实现的
public final class RealAdd implements AddInterface {
// $FF: synthetic field
//这里创建了实现类的变量即by后面的 AddImp()
private final AddImp $$delegate_0 = new AddImp();
//实现了Addinterface的接口
public int add(int a, int b) {
//返回的是实现类的add方法调用结果
return this.$$delegate_0.add(a, b);
}
}
另一种写法
class RealAdd2(add:AddInterface):AddInterface by add
转换为java
public final class RealAdd2 implements AddInterface {
// $FF: synthetic field
private final AddInterface $$delegate_0;
public RealAdd2(@NotNull AddInterface add) {
Intrinsics.checkNotNullParameter(add, "add");
super();
this.$$delegate_0 = add;
}
public int add(int a, int b) {
return this.$$delegate_0.add(a, b);
}
}
从上面可以看到kotlin的by关键子可以帮我们完成样板代码的编写,省去了很多时间,提高了开发效率。
四、委托属性
通过by关键字将string变量的值交给Data处理,即string的set()
,get()
方法实际操作的是Data
类中的getValue
和setValue
方法。
var string:String by Data()
Data类一定要实现getValue
和setValue
方法
class Data {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String =
"$thisRef, thank you for delegating '${property.name}' to me!"
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) =
println("$value has been assigned to '${property.name}' in $thisRef.")
}
这样手敲getValue
和setValue
方法比较麻烦,但是系统已经提供了相应的api给我们使用,通过系统api可以提高开发效率。
public interface ReadWriteProperty<in T, V> : ReadOnlyProperty<T, V> {
public override operator fun getValue(thisRef: T, property: KProperty<*>): V
public operator fun setValue(thisRef: T, property: KProperty<*>, value: V)
}
我们实现这个接口
class Data<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
}
}
也可以不实现接口 直接使用Delegates.notNull()
var string:String by Delegates.notNull()
看下Delegates的代码
public object Delegates {
/**
* 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.
*
* @sample samples.properties.Delegates.notNullDelegate
*/
public fun <T : Any> notNull(): ReadWriteProperty<Any?, T> = NotNullVar()
/**
* Returns a property delegate for a read/write property that calls a specified callback function when changed.
* @param initialValue the initial value of the property.
* @param onChange the callback which is called after the change of the property is made. The value of the property
* has already been changed when this callback is invoked.
*
* @sample samples.properties.Delegates.observableDelegate
*/
public inline fun <T> observable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit):
ReadWriteProperty<Any?, T> =
object : ObservableProperty<T>(initialValue) {
override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = onChange(property, oldValue, newValue)
}
/**
* Returns a property delegate for a read/write property that calls a specified callback function when changed,
* allowing the callback to veto the modification.
* @param initialValue the initial value of the property.
* @param onChange the callback which is called before a change to the property value is attempted.
* The value of the property hasn't been changed yet, when this callback is invoked.
* If the callback returns `true` the value of the property is being set to the new value,
* and if the callback returns `false` the new value is discarded and the property remains its old value.
*
* @sample samples.properties.Delegates.vetoableDelegate
* @sample samples.properties.Delegates.throwVetoableDelegate
*/
public inline fun <T> vetoable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Boolean):
ReadWriteProperty<Any?, T> =
object : ObservableProperty<T>(initialValue) {
override fun beforeChange(property: KProperty<*>, oldValue: T, newValue: T): Boolean = onChange(property, oldValue, newValue)
}
}
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
}
}
上面的源码中包含了3个委托方法,下面我们来一个一个讲解。
- notNull()
返回一个可读写的委托属性,在获取委托属性的值时要先进行初始化,否则抛出异常。 - observable()
监听值得改变,当值变化时可以在监听中处理逻辑
var value:String by Delegates.observable(""){property, oldValue, newValue -> Log.i("test ", "oldValue=${oldValue},newValue=$newValue") }
- vetoable
监听值的变化,并自己处理要不要修改值
public inline fun <T> vetoable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Boolean):
ReadWriteProperty<Any?, T> =
object : ObservableProperty<T>(initialValue) {
override fun beforeChange(property: KProperty<*>, oldValue: T, newValue: T): Boolean = onChange(property, oldValue, newValue)
}
五、委托函数
通过by关键字使一个函数将自己的执行逻辑交给另一个函数来实现,而不是在自己的函数体中实现。这样可以避免重复编写一些常见的函数逻辑,例如日志、缓存、错误处理等。
// 定义一个委托函数,它接收两个Int参数,并返回一个Int结果
fun add(a: Int, b: Int): Int {
return a + b
}
// 定义一个使用by关键字声明的变量,它的类型是一个函数类型,并且会将自己的执行逻辑委托给add函数
var sum: (Int, Int) -> Int by ::add
fun main() {
// 调用sum变量时,会调用add函数
println(sum(1, 2))
}
六、延迟委托
使用by lazy延迟加载,例如字符串变量的延迟加载,只有在使用时才会进行初始化值。
val ss : String by lazy{
println("computed!")
"Hello"
}
我们将下面的代码转成java代码看下
class Test {
val ss : String by lazy{
println("computed!")
"Hello"
}
fun test(){
var a = ss
}
}
转为java
public final class Test {
@NotNull
private final Lazy ss$delegate;
@NotNull
public final String getSs() {
Lazy var1 = this.ss$delegate;
Object var3 = null;
return (String)var1.getValue();
}
public final void test() {
String a = this.getSs();
}
public Test() {
this.ss$delegate = LazyKt.lazy((Function0)null.INSTANCE);
}
}
可以看到ss这个变量转换成了Lazy ss$delegate
,并提供了一个getSs方法,test()
方法中通过getSs()
方法给a赋值。Lazy ss$delegate
的初始化放在了构造函数中。查看LazyKt.lazy
方法源码
public actual fun <T> lazy(initializer: () -> T): Lazy<T> = SynchronizedLazyImpl(initializer)
发现是将initializer
这个Lambda参数传入了SynchronizedLazyImpl
类中,这个类实现了Lazy接口,那么上文中的getSs()
方法实际调用的是SynchronizedLazyImpl
类中复写的value的get方法。
private class SynchronizedLazyImpl<out T>(initializer: () -> T, lock: Any? = null) : Lazy<T>, Serializable {
private var initializer: (() -> T)? = initializer
@Volatile private var _value: Any? = UNINITIALIZED_VALUE
// final field is required to enable safe publication of constructed instance
private val lock = lock ?: this
override val value: T
get() {
// 初始化过了就直接返回值
val _v1 = _value
if (_v1 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST")
return _v1 as T
}
//当value没有被初始化时,加锁通过lambda表达式赋值
return synchronized(lock) {
//再判断一次是否初始化过value
val _v2 = _value
if (_v2 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST") (_v2 as T)
} else {
val typedValue = initializer!!()
_value = typedValue
initializer = null
typedValue
}
}
}
override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
private fun writeReplace(): Any = InitializedLazyImpl(value)
}
由以上代码可知ss的属性值委托给了Lazy实现类,并在第一次调用get方法时对value进行初始化,并且对value的初始化时线程安全的,因为加了同步锁。