delegate and owner
A closure holds three references: this is the class that contains it, owner is the closure or class it was defined in, and delegate is where an unknown method is looked up. By default the delegate is the owner.
The three objects
three.groovy
class Speaker {
String prefix = '>>'
void say(String text) {
println "${prefix} ${text}"
}
}
def speaker = new Speaker()
def block = { say 'hello' }
println block.delegate == block.owner
println block.delegate.getClass().name == 'three'
block.delegate = speaker
block.resolveStrategy = Closure.DELEGATE_FIRST
println block.delegate.getClass().simpleName
block()
groovy three.groovy
true
true
Speaker
>> hello
say is not a method of the script, so the call is resolved against the delegate. With the default OWNER_FIRST strategy the owner is asked first and the call fails; DELEGATE_FIRST asks the delegate first, which is how a builder makes its methods available inside a block. The second line is true because the owner of the closure is the script object itself, and the compiler names a script class after its file, which the groovyc lesson shows in the class file.
The four strategies
- OWNER_FIRST is the default: the owner answers, then the delegate.
- DELEGATE_FIRST asks the delegate, then the owner.
- OWNER_ONLY never asks the delegate.
- DELEGATE_ONLY never asks the owner, which is what a DSL uses when a name must always mean the block's object.
An owner and a delegate that differ
nested.groovy
class Counter {
int value = 0
void add(int n) {
value += n
}
}
def counter = new Counter()
def outer = {
def inner = {
add 5
}
inner.delegate = counter
inner.resolveStrategy = Closure.DELEGATE_ONLY
inner()
}
outer()
println counter.value
groovy nested.groovy
5
The inner closure has the outer closure as its owner, so its default delegate would be the outer closure. Setting the delegate to the counter and the strategy to DELEGATE_ONLY points every unknown name at the counter, and the call reaches add.
Related
- Builders: the real use of a delegate.
- A small DSL: a builder of your own.
Автор статьи: Arthur Isaev