Kotlin委托

举报
yd_221104950 发表于 2020/12/03 22:36:10 2020/12/03
【摘要】 Kotlin这语言有一个特点,它直接支持一些特别有用的设计模式在里面,如Kotlin的对象声明(单例),我们今天讲它的另外一种:委托。 在委托设计模式中,有两个对象参与处理同一个请求,接受请求的对象将请求委托给另一个对象来处理。许多其他设计模式,如状态模式、策略模式、访问者模式实际上也采用了委托模式。委托模式使得我们可以用聚合来替代继承,它还使我们可以模拟mixin。...

Kotlin这语言有一个特点,它直接支持一些特别有用的设计模式在里面,如Kotlin的对象声明(单例),我们今天讲它的另外一种:委托。

在委托设计模式中,有两个对象参与处理同一个请求,接受请求的对象将请求委托给另一个对象来处理。许多其他设计模式,如状态模式、策略模式、访问者模式实际上也采用了委托模式。委托模式使得我们可以用聚合来替代继承,它还使我们可以模拟mixin。举个例子:
模拟打印机Printer拥有针式打印机RealPrinter的实例,Printer拥有的方法print()将处理转交给RealPrinter的方法print(),也说是Printer委托RealPrinter来做print()这件事。

class RealPrinter { // the "delegate" void print() { System.out.print("something"); }
 } class Printer { // the "delegator" RealPrinter p = new RealPrinter(); // create the delegate void print() { p.print(); // delegation } 
 } public class Main { // to the outside world it looks like Printer actually prints. public static void main(String[] args) { Printer printer = new Printer(); printer.print(); }
 }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

Kotlin中的委托

Kotlin 直接支持委托模式,更加优雅,简洁。Kotlin 通过关键字 by 实现委托。

类委托

类的委托即一个类中定义的方法实际是调用另一个类的对象的方法来实现的。

以下实例中派生类 Derived 继承了接口 Base 所有方法,并且委托一个传入的 Base 类的对象来执行这些方法。

// 创建接口
interface Base { fun print()
}

// 实现此接口的被委托的类
class BaseImpl(val x: Int) : Base { override fun print() { print(x) }
}

// 通过关键字 by 建立委托类
class Derived(b: Base) : Base by b

fun main(args: Array<String>) { val b = BaseImpl(10) Derived(b).print() // 输出 10
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

by 子句表示,将 b 保存在 Derived 的对象实例内部,而且编译器将会生成继承自 Base 接口的所有方法, 并将调用转发给 b。

属性委托

属性委托指的是一个类的某个属性值不是在类中直接进行定义,而是将其托付给一个代理类,从而实现对该类的属性统一管理。

属性委托语法格式:

val/var <属性名>: <类型> by <表达式>

  
 
  • 1
var/val:属性类型(可变/只读)
属性名:属性名称
类型:属性的数据类型
表达式:委托代理类

  
 
  • 1
  • 2
  • 3
  • 4

by 关键字之后的表达式就是委托, 属性的 get() 方法(以及set() 方法)将被委托给这个对象的 getValue() 和 setValue() 方法。属性委托不必实现任何接口, 但必须提供 getValue() 函数(对于 var属性,还需要 setValue() 函数)。

// 定义包含属性委托的类
class Example { var p: String by Delegate()
}

// 委托的类
class Delegate { operator fun getValue(thisRef: Any?, property: KProperty<*>): String { return "$thisRef, 这里委托了 ${property.name} 属性" } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { println("$thisRef${property.name} 属性赋值为 $value") }
}
fun main(args: Array<String>) { val e = Example() println(e.p) // 访问该属性,调用 getValue() 函数 e.p = "Runoob"   // 调用 setValue() 函数 println(e.p)
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

标准委托

Kotlin 的标准库中已经内置了很多工厂方法来实现属性的委托。

延迟初始化属性 Lazy

val lazyValue: String by lazy { println("computed!") // 第一次调用输出,第二次调用不执行 "Hello"
}

fun main(args: Array<String>) { println(lazyValue)   // 第一次执行,执行两次输出表达式 println(lazyValue)   // 第二次执行,只输出返回值
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

可观察属性 Observable

observable 可以用于实现观察者模式。
Delegates.observable() 函数接受两个参数: 第一个是初始化值, 第二个是属性值变化事件的响应器(handler)。
在属性赋值后会执行事件的响应器(handler),它有三个参数:被赋值的属性、旧值和新值:

import kotlin.properties.Delegates

class User { var name: String by Delegates.observable("初始值") { prop, old, new -> println("旧值:$old -> 新值:$new") }
}

fun main(args: Array<String>) { val user = User() user.name = "第一次赋值" user.name = "第二次赋值"
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

把属性储存在映射中

一个常见的用例是在一个映射(map)里存储属性的值。 这经常出现在像解析 JSON 或者做其他"动态"事情的应用中。 在这种情况下,你可以使用映射实例自身作为委托来实现委托属性。

class Site(val map: Map<String, Any?>) { val name: String by map val url: String  by map
}

fun main(args: Array<String>) { // 构造函数接受一个映射参数 val site = Site(mapOf( "name" to "菜鸟教程", "url"  to "www.runoob.com" )) // 读取映射值 println(site.name) println(site.url)
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

Not Null

notNull 适用于那些无法在初始化阶段就确定属性值的场合。

class Foo { var notNullBar: String by Delegates.notNull<String>()
}

foo.notNullBar = "bar"
println(foo.notNullBar)

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

需要注意,如果属性在赋值前就被访问的话则会抛出异常

局部委托属性

可以将局部变量声明为委托属性。 例如,可以使一个局部变量惰性初始化

fun example(computeFoo: () -> Foo) { val memoizedFoo by lazy(computeFoo) if(someCondition && memoizedFoo.isValid()) { memoizedFoo.doSomething() }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

文章来源: blog.csdn.net,作者:WongKyunban,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/weixin_40763897/article/details/110289346

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。