我经常看到一种模式,用于在我们访问对象之前需要执行查找代码的情况。使用此模式时,通常以单词 with
开头。 .
例如,我们需要从数据库中检索客户记录,然后才能使用它们:
def withCustomer (id, closure) {
def customer = getCustomer(id)
closure(customer)
}
withCustomer(12345) { customer ->
println "Found customer $customer.name"
}
Groovy 在闭包或匿名函数之间没有这样的区别。或许,我可以问一下这种带有匿名函数的模式是否有名称。
最佳答案
这就是策略模式。闭包保存了一些作为参数传递给函数的行为,以便函数可以接受不同的行为。参见 Peter Norvig 的演讲 Design Patterns in Dynamic Languages :
The strategy is a variable whose value is a function (E.g., with first-class functions, pattern is invisible)
关于design-patterns - 这种带有闭包的模式有名字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10032810/