代理
by代理
只有接口才能实现by代理,类是不行的
fun BaseMain() {
var dog = Animal("Dog")
Delegation(dog).run()
}
class Animal(name: String) : IAniaml {
var name = name
override fun run() {
println("This animal ${name}is running now.Please go for a look.")
}
}
interface IAniaml {
fun run()
}
class Delegation(a: IAniaml) : IAniaml by a
/**
打印
This animal Dogis running now.Please go for a look.
*/
重写代理方法
当重写属性时,并不会改变传入的类的属性,如果前面有用到该类的方法时,不会受影响,
fun BaseMain() {
var dog = Animal("Dog")
var delDog = Delegation(dog)
delDog.run()
delDog.jump()
}
class Animal(override var name: String) : IAniaml {
override fun jump() {
println("I can jump,I can high.")
}
init {
this.name = name
}
override fun run() {
println("This animal ${name} is running now.Please go for a look.")
}
}
interface IAniaml {
var name: String
fun run()
fun jump()
}
class Delegation(a: IAniaml) : IAniaml by a {
override var name = "Large Dog"
override fun jump() {
println("This is good at you. This is $name")
}
}
/**
打印
This animal Dog is running now.Please go for a look.
This is good at you. This is Large Dog
*/
属性代理
- 一般情况
就是属性的监听器,虽然简单,但是还是有点不理解的是,不知道怎么获取属性值。。。。。fuck!
fun BaseMain() {
var ani = Animal()
ani.x = "this"
println(ani.x)
ani.x = "112"
}
class Animal {
var x: String by Dog()
}
class Dog {
operator fun getValue(thisRef: Any?, pr: KProperty<*>): String {
return "This is property name of ${pr.name}"
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("value is $value")
}
}
- 其他见下节