15-委托
14.5.2 委托
委托可以说是Gradle选择Groovy作为DSL执行平台的一个重要因素,通过Groovy提供的委托机制,Gradle可以很简单地定制一个控制结构体。代码如下。
email {
from '[email protected]'
to '[email protected]'
subject 'The pope has resigned!'
body {
p 'Really, the pope has resigned!'
}
}
如果将上述代码转换成DSL语言,则其代码如下。
def email(Closure cl) {
def email = new EmailSpec()
def code = cl.rehydrate(email, this, this)
code.resolveStrategy = Closure.DELEGATE_ONLY
code()
}
通过转换后的DSL语言可以发现,该段代码定义了一个email(Closure cl)方法,EmailSpec是继承了参数中cl闭包里所有方法(比如from、to等函数)的一个类,通过rehydrate方法将cl复制成一份新的实例并赋值给code,在rehydrate方法中设置delegate、owner和thisObject 3个属性,将cl和email两者关联起来并赋予一种委托关系。这种委托关系可以理解为,cl闭包中的from、to等方法会调用email委托类实例中的方法,而且可以访问email中的实例变量。DELEGATE_ONLY表示闭包方法调用只会委托给它的委托者,最后使用code()执行闭包中的方法。