Kotlin委托(Delegation)笔记

作者: dengyin2000 | 来源:发表于2018-03-03 01:36 被阅读112次

    Kotlin语言基础笔记

    Kotlin流程控制语句笔记

    Kotlin操作符重载与中缀表示法笔记

    Kotlin扩展函数和扩展属性笔记

    Kotlin空指针安全(null-safety)笔记

    Kotlin类型系统笔记

    Kotlin面向对象编程笔记

    Kotlin委托(Delegation)笔记

    Kotlin泛型型笔记

    Kotlin函数式编程笔记

    Kotlin与Java互操作笔记

    Kotlin协程笔记

    委托模式也叫做代理模式,这是一个非常常用的设计模式,代理模式使得可以用聚合来替代继承(这个也是Effective Java中推荐的方式)。怎么解释代理模式呢?举个海外代购的例子,假如小红有个哥哥小明在米国,小红身边的很多姐妹都非常喜欢coach,gucci的包,但是国内太贵,所以身边的姐妹都会委托小红找她哥哥在米国买好寄回国内。小红和哥哥也能从中获取一些回扣,身边的姐妹也能得到实惠。小红就是代理,代理商。OK,我们用Java代码来描述下:

    public interface Buyer {
        
        void buyCoach();
    
        void buyGucci();
    }
    
    public class XiaoMing implements Buyer {
        @Override
        public void buyCoach() {
            System.out.println("XiaoMing buy Coach!");
        }
    
        @Override
        public void buyGucci() {
            System.out.println("XiaoMing buy Gucci!");
        }
    }
    
    public class XiaoHong implements Buyer {
    
        private Buyer xiaoMing;
    
        public XiaoHong(Buyer xiaoMing) {
            this.xiaoMing = xiaoMing;
        }
    
        @Override
        public void buyCoach() {
            System.out.println("Brother, please buy Coach for me.");
            xiaoMing.buyCoach();
            System.out.println("Thanks Brother, I will give some money to you.");
        }
    
        @Override
        public void buyGucci() {
            System.out.println("Brother, please buy Gucci for me.");
            xiaoMing.buyGucci();
            System.out.println("Thanks Brother, I will give some money to you.");
        }
    
        public static void main(String[] args) {
            Buyer xiaoHong = new XiaoHong(new XiaoMing());
            xiaoHong.buyCoach();
            xiaoHong.buyGucci();
        }
    }
    

    运行上面的代码,输出:

    Brother, please buy Coach for me.
    XiaoMing buy Coach!
    Thanks Brother, I will give some money to you.
    
    Brother, please buy Gucci for me.
    XiaoMing buy Gucci!
    Thanks Brother, I will give some money to you.
    

    1. 类的委托

    Kotlin在语言层面原生支持委托模式。上面的Java改写如下:

    interface Buyer{
        fun buyCoach()
    
        fun buyGucci()
    }
    
    class XiaoMing : Buyer{
        override fun buyCoach() {
            println("XiaoMing buy Coach!")
        }
    
        override fun buyGucci() {
            println("XiaoMing buy Gucci!")
        }
    }
    
    class XiaoHong(val realBuyer: Buyer) : Buyer by realBuyer {
    
        override fun buyCoach() {
            println("Brother, please buy Coach for me.")
            realBuyer.buyCoach()
            println("Thanks Brother, I will give some money to you.")
        }
    
        override fun buyGucci() {
            println("Brother, please buy Gucci for me.")
            realBuyer.buyGucci()
            println("Thanks Brother, I will give some money to you.")
        }
    
    }
    
    fun main(args: Array<String>) {
        val xiaoHong = XiaoHong(XiaoMing())
        xiaoHong.buyCoach()
        xiaoHong.buyGucci()
    }
    

    请注意by realBuyer 表示XiaoHong的所有共有方法委托给一个指定的对象readlBuyer。如果你不想要XiaoHong说太多废话的话,你可以用简单的一行代码定义XiaoHong:

    class XiaoHong(val realBuyer: Buyer) : Buyer by realBuyer
    

    这就是所谓的在语言层面支持委托,确实比Java简洁太多。

    2. 属性委托

    对于Kotlin类中的属性,我们也可以使用委托来赋予属性一些牛逼的特性,这些特性在Java中可能需要我们写很多代码来实现,但是在Kotlin中一切将变得so easy!

    2.1 属性的委托

    看一个例子:

    
    class DelegatePropertiesDemo {
        var content: String by Content()
    
        override fun toString(): String {
            return "DelegatePropertiesDemo Class"
        }
    }
    
    class Content {
        operator fun getValue(delegatePropertiesDemo: DelegatePropertiesDemo, property: KProperty<*>): String {
            return "${delegatePropertiesDemo} property '${property.name}' = 'Balalala ... ' "
        }
    
        operator fun setValue(delegatePropertiesDemo: DelegatePropertiesDemo, property: KProperty<*>, value: String) {
            println("${delegatePropertiesDemo} property '${property.name}' is setting value: '$value'")
        }
    }
    
    fun main(args: Array<String>) {
        val delegatePropertiesDemo = DelegatePropertiesDemo()
        println(delegatePropertiesDemo.content)
    
        delegatePropertiesDemo.content = "abc"
    }
    

    运行上面例子输出:

    DelegatePropertiesDemo Class property 'content' = 'Balalala ... ' 
    DelegatePropertiesDemo Class property 'content' is setting value: 'abc'
    

    上面这个例子可以看出,DelegatePropertiesDemo的content属性的getter/setter是分别委托给下面这个Content类的getValue和setValue方法。注意getValue和setValue方法必须要使用operator修饰。

    2.2 懒加载属性委托 lazy()函数

    我们先来看看lazy()函数的定义:


    lazy

    它接收一个lambda表达式,并返回一个Lazy<T>的实例函数,返回的实例可以实现懒加载属性的委托,第一次调用记录下结果,后续调用会返回第一次调用的结果。
    第二个方法是的第一个参数是线程安全模式,默认是线程安全的。

    fun main(args: Array<String>) {
        val firstTimestamp by lazy { System.currentTimeMillis() }
        println(firstTimestamp)
        Thread.sleep(1000)
        println(firstTimestamp)
    }
    

    输出的两次时间戳是一样的。

    1520010381034
    1520010381034
    

    如果委托多个线程同时执行,不需要同步锁,可以使用LazyThreadSafetyMode.PUBLICATION参数。
    如果是在单线程环境中,可以使用LazyThreadSafetyMode.NONE参数,这也是性能最高。

    2.3 可观察属性委托

    我们把属性委托给Delegates.observable函数,当属性被赋值时,会触发其中的回调函数onChange。

    observable
    fun main(args: Array<String>) {
        var level:String by Delegates.observable("P0", {property: KProperty<*>, oldValue: String, newValue: String -> println("$oldValue -> $newValue") })
    }
    

    输出:

    P0 -> P1
    P1 -> P2
    P2 -> P3
    

    2.4 可否决属性委托

    函数定于如下:


    vetoable

    可以通过onChange函数返回值是否为true,来让属性的值是否需要变化。

    class PostHierarchy {
        var grade: String by Delegates.vetoable("T0", {
            property, oldValue, newValue ->
            true
        })
    
        var notChangeGrade: String by Delegates.vetoable("T0", {
            property, oldValue, newValue ->
            false
        })
    }
    
    val ph = PostHierarchy()
    ph.grade = "T1"
    ph.grade = "T2"
    ph.grade = "T3"
    println(ph.grade) // 打印T3
    
    ph.notChangeGrade = "T1"
    ph.notChangeGrade = "T2"
    ph.notChangeGrade = "T3"
    println(ph.notChangeGrade) // 打印T0
    

    2.5 非空属性委托

    var name: String by Delegates.notNull()
    

    这样name属性就被限制为不能为null,如果被赋值null,编译器直接报错:

    2.6 属性委托给Map

    我们也可以把一个类中的属性委托给Map:

    class User(val map: MutableMap<String, Any?>){
        var name:String by map
        var age:Int by map
    
        override fun toString(): String {
            return "User(name = $name, age = $age)"
        }
    }
    
    fun main(args: Array<String>) {
        val user = User(mutableMapOf(
                "name" to "Denny Deng",
                "age" to 34
        ))
        println(user)
        user.age = 36
        println(user.map["age"])
    }
    

    输出:

    User(name = Denny Deng, age = 34)
    36
    

    你可以看到修改了map的值,能影响到user的name和age属性,修改了user的属性值也能影响到map的值。

    相关文章

      网友评论

      本文标题:Kotlin委托(Delegation)笔记

      本文链接:https://www.haomeiwen.com/subject/lwwzxftx.html