1议街,class委托
interface Animal{
fun call()
}
class Cat : Animal{
override fun call() {
println("喵喵喵")
}
}
class Dog : Animal{
override fun call() {
println("汪汪汪")
}
}
//委托實(shí)現(xiàn)策略模式
//MagicAnimal行為由傳入的Animal實(shí)例實(shí)現(xiàn)
class MagicAnimal(val animal: Animal) : Animal by animal
fun main(args: Array<String>){
println("output:")
MagicAnimal(Dog()).call()
MagicAnimal(Cat()).call()
}
output:
汪汪汪
喵喵喵
2斥黑,屬性委托
//委托實(shí)現(xiàn)策略模式
//MagicAnimal行為由傳入的Animal實(shí)例實(shí)現(xiàn)
class MagicAnimal(val animal: Animal) : Animal by animal {
//name屬性訪問由代理PropertyDelegation處理
var name: String by PropertyDelegation()
}
class PropertyDelegation{
private lateinit var name : String
operator fun getValue(thisRef: Any?, property: KProperty<*>): String{
println("name=$name")
return name
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String){
println("value=$value")
name = value
}
}
fun main(args: Array<String>){
println("output:")
var mCat = MagicAnimal(Cat())
mCat.name = "花花"
}
output:
value=花花