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

Groovy笔记(二)闭包

发布时间:2020-12-14 16:44:07 所属栏目:大数据 来源:网络整理
导读:闭包应用模式: 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 Reso

闭包应用模式:

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}
}

(编辑:李大同)

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

    推荐文章
      热点阅读