Groovy笔记(二)闭包

闭包应用模式:

1.策略模式:

def function (Closure clo) {
	for (i in 1..n) {
		clo(i)
	}
}
function { i->
	println i**2
}
function { i->
	println i**3
}

2.闭包参数:

def closure = {Date d,String str-> //TODO}
closure new Date(),"String"

3.模板方法模式:

class Resouces {
	def open() {}
	def write() {}
	def read() {}
	def close() {}

	def static use(Resources r,Closure clo) {
		try {
			r.open()
			clo(r)
			r.close()
		} catch(ex) {}
	}
}
def res = new Resources()
Resources.use {r,{r->r.write()}}
Resources.use {r,{r->r.read()}}

4.闭包参数

Closure.maximumNumberOfParameters 表示参数个数

Closure.parameterTypes 表示闭包参数类型


5.闭包参数

owner:代表闭包的外层包如果没有,就是闭包本身

this:永远指向闭包最外层的类

delegate:闭包委托类


6.闭包调用

a.closure()

b.closure.call()


7.闭包在集合类中的应用

any(Closure):判断是否存在

every(Closure):判断是否每个都是

collect(Closure):遍历整个集合,通过Closure里面的算法替换集合里的元素

<span style="font-family:Helvetica Neue;">def result = [1,2,3,4].collect {
	i->i**2
}
println result // [1,4,9,16]</span>

8.闭包作为返回值

def multiply(x) {
	return {y->return x*y}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值