2018年7月31日 星期二

this、owner、delegate (Groovy 2.x 四)


class MyGroovy {
    class InnerGroovy {
        static def staticClouser = {
            println "a ${this}" // 閉包定義的類
            println "b ${owner}" // 閉包定義的類或物件
            println "c ${delegate}" // 預設和 owner 一樣
        }
    
        def static methodStaticClouser() {
            def xxx = {
                println "d ${this}"
                println "e ${owner}"
                println "f ${delegate}"
            }
            xxx.call()
        }
    }
    
    static void main(def args) {
        MyGroovy.InnerGroovy.staticClouser.call()
        MyGroovy.InnerGroovy.methodStaticClouser()
    }
}

※結果:
a class MyGroovy
b class MyGroovy$InnerGroovy
c class MyGroovy$InnerGroovy
d class MyGroovy
e class MyGroovy$InnerGroovy
f class MyGroovy$InnerGroovy



class Animal{}
    
class MyGroovy {
    static def staticClouser = {
        println "a ${this}" // 閉包定義的類
        println "b ${owner}" // 閉包定義的類或物件
        println "c ${delegate}" // 預設和 owner 一樣
    }
    
    static def methodStaticClouser() {
        def xxx = {
            println "d ${this}"
            println "e ${owner}"
            println "f ${delegate}"
        }
        xxx.delegate = new Animal()
        xxx.call()
    }
    
    static void main(def args) {
        MyGroovy.staticClouser.call()
        MyGroovy.methodStaticClouser()
    }
}

※結果:
a class MyGroovy
b class MyGroovy
c class MyGroovy
d class MyGroovy
e class MyGroovy
f Animal@3745e5c6



class Animal {
    String name
}
    
class MyGroovy {
    Integer id
    String name
    Double price
    
    def show = {
        "編號${id},名稱${name},價錢為${price}"
    }
    
    String display() {
        println show.call()
    }
    
    static void main(String[] args) {
        MyGroovy m1 = new MyGroovy(price: 50.2, name: '西洋棋', id: 1)
        MyGroovy m2 = new MyGroovy(name: '象棋', id: 2)
        Animal a = new Animal(name: '老虎')
        m1.display()
        m1.show.delegate = a
        m1.show.resolveStrategy = Closure.DELEGATE_FIRST // 預設為 0,也就是 OWNER_FIRST
        m1.display()
        m2.display()
    }
}

※有點像 javascript 的 call、apply、bind

沒有留言:

張貼留言