[英]What are the use cases for `Delegates.observable` when we have property setters?
What are the use cases for Delegates.observable
when we can just use property setters?当我们只能使用属性设置器时,
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.
}
Property setters require much more code duplication if you want multiple properties to react to modification in the same way:如果您希望多个属性以相同的方式对修改做出反应,则属性设置器需要更多的代码重复:
var foo: Foo = Foo()
set(value) {
println("foo = $value")
field = value
}
var bar: Bar = Bar()
set(value) {
println("bar = $value")
field = value
}
Delegates, in turn, are aimed to allow for reuse of the property accessors logic, like this:反过来,委托旨在允许重用属性访问器逻辑,如下所示:
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())
Delegates.observable are commonly used in Android. Delegates.observable 在 Android 中常用。 One such such case is adding text change listener.
一种这样的情况是添加文本更改侦听器。
Example示例
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)
}
}
Usage用法
val textView = TextView()
textView.listener = PrintingTextChangedListener()
textView.text = "Lorem ipsum"
textView.text = "dolor sit amet"
Output输出
Text is changed to: Lorem ipsum
文字改为:Lorem ipsum
Text is changed to: dolor sit amet
文字改为:dolor sat amet
You can read more patterns here: https://github.com/dbacinski/Design-Patterns-In-Kotlin您可以在此处阅读更多模式: https : //github.com/dbacinski/Design-Patterns-In-Kotlin
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.