design-patterns - 这种带有闭包的模式有名字吗?

标签 design-patterns language-agnostic groovy closures terminology

我经常看到一种模式,用于在我们访问对象之前需要执行查找代码的情况。使用此模式时,通常以单词 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/

相关文章:

java - 代码中有一些设计模式吗?

algorithm - 紧凑的数据结构,如集合

java - Groovy 脚本错误 : java. io.NotSerializedException : com. xlson.groovycsv.CsvIterator

Jenkins 共享库 : "java.lang.NoSuchMethodError: No such DSL method"

groovy - 无法在NetBeans 6.5中运行Groovy单元测试

java - 关联关系中调用父方法

user-interface - 什么是 MVP 和 MVC,有什么区别?

java - 有一个sql PreparedStatement池有意义吗?

language-agnostic - 在散点列表中查找路径的算法

language-agnostic - 您要解决(编程)问题的Modus Operandi是什么?