Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a name for this pattern with closures?

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.

like image 793
Arturo Herrero Avatar asked Apr 05 '12 16:04

Arturo Herrero


1 Answers

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)

like image 108
Nathan Hughes Avatar answered Sep 24 '22 12:09

Nathan Hughes