当我们可以使用属性设置器时,Delegates.observable
有哪些用例?
var foo by Delegates.observable("hell0") { prop, old, new ->
// react to changes in foo
}
var bar = "hello"
set(value) {
field = value
// react to changes in bar
// we can also do validation, set something like `value*2` to field, etc.
}
答案 0 :(得分:10)
如果您希望多个属性以相同的方式对修改做出反应,则属性设置器需要更多的代码重复:
var foo: Foo = Foo()
set(value) {
println("foo = $value")
field = value
}
var bar: Bar = Bar()
set(value) {
println("bar = $value")
field = value
}
反过来,代表的目的是允许重用属性访问器逻辑,如下所示:
fun <T> printDelegate(init: T) =
Delegates.observable(init) { prop, _, new ->
println("${prop.name} = $new")
}
val foo: Foo by printDelegate(Foo())
val bar: Bar by printDelegate(Bar())
答案 1 :(得分:1)
Delegates.observable通常在Android中使用。一种这样的情况是添加文本更改侦听器。
示例
interface TextChangedListener {
fun onTextChanged(newText: String)
}
class PrintingTextChangedListener : TextChangedListener {
override fun onTextChanged(newText: String) = println("Text is changed to: $newText")
}
class TextView {
var listener: TextChangedListener? = null
var text: String by Delegates.observable("") { prop, old, new ->
listener?.onTextChanged(new)
}
}
用法
val textView = TextView()
textView.listener = PrintingTextChangedListener()
textView.text = "Lorem ipsum"
textView.text = "dolor sit amet"
输出
文本更改为:Lorem ipsum
文本更改为:dolor sit amet
您可以在此处阅读更多模式: https://github.com/dbacinski/Design-Patterns-In-Kotlin