加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

设计模式 – 这个模式的名称是否有闭包?

发布时间:2020-12-14 16:25:33 所属栏目:大数据 来源:网络整理
导读:我经常看到在我们有访问对象之前需要执行的查找代码的情况下使用的模式.使用此模式时,通常以单词with开头. 例如,在我们可以使用之前,我们需要从数据库中检索客户记录: def withCustomer (id,closure) { def customer = getCustomer(id) closure(customer)}w
我经常看到在我们有访问对象之前需要执行的查找代码的情况下使用的模式.使用此模式时,通常以单词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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读