I often see a pattern used in circumstances where we have look-up code that needs to be executed before we have access to an object. When using this pattern, usually begins with the word with
.
For example, we have customer records that need to be retrieved from a database before we can use them:
def withCustomer (id, closure) {
def customer = getCustomer(id)
closure(customer)
}
withCustomer(12345) { customer ->
println "Found customer $customer.name"
}
Groovy makes no such distinction between closures or anonymous functions. Perhaps, I could ask if there is a name for this pattern with anonymous functions.
This is the Strategy pattern. The closure holds some piece of behavior to be passed into the function as an argument, so that the function can accept different behaviors. See Peter Norvig's presentation Design Patterns in Dynamic Languages:
The strategy is a variable whose value is a function (E.g., with first-class functions, pattern is invisible)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With