1,class委托
interface Animal{
fun call()
}
class Cat : Animal{
override fun call() {
println("喵喵喵")
}
}
class Dog : Animal{
override fun call() {
println("汪汪汪")
}
}
//委托实现策略模式
//MagicAnimal行为由传入的Animal实例实现
class MagicAnimal(val animal: Animal) : Animal by animal
fun main(args: Array<String>){
println("output:")
MagicAnimal(Dog()).call()
MagicAnimal(Cat()).call()
}
output:
汪汪汪
喵喵喵
2,属性委托
//委托实现策略模式
//MagicAnimal行为由传入的Animal实例实现
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=花花
网友评论