本文链接:https://blog.youkuaiyun.com/feather_wch/article/details/131618022
/***===============================
* 闭包
* 1、闭包是什么?匿名内联函数,也称为闭包
* 2、闭包是函数内部和外部的桥梁
*
* 闭包一般不会直接使用,而是作为参数传入
* 闭包具有的关键变量:
* 1. this
* 2. owner
* 3. delegate
* 4. 闭包的委托策略
*=================================*/
def closure={
println("hello")
}
closure() // 方法1
closure.call()
// 参数闭包
def closeureParam={String name, int age->
println("name:$name:age:$age")
}
closeureParam.call("wch", 20)
// 内置参数 it
def closureIt={
println "hello it=$it"
return it
}
closureIt.call("wch")
// 返回值
def result = closureIt.call("feather")
println(result)
// 基本数据类型API 1.upto(n, xxx) 1~n
int n1 = fab(3)
int fab(int number){
int result = 1;
1.upto(number, { num-> result *= num})
return result
}
println(n1)
// 基本数据类型API n.downto(1, xxx) n~1
int fab2(int n){
int result = 1
n.downto(1){
result *= it
}
return result
}
int n2 = fab2(5)
println(n2)
// 基本数据类型API 5.times 1,2,3,4 < size(5)
int sum(int n){
int result = 0
n.times {
result += it
}
return result
}
println(sum(5))
// String each
String strEach = "math: 2 + 3 = 5"
strEach.each { s->
if(s.isNumber())println(s)
// 每个字符复重复2个
s.multiply(2)
}
// String find查找符合条件的第一个字符
println strEach.find{
it.isNumber()
}
// String findAll 符合的所有字符
def list = strEach.findAll{
it.isNumber()
}
println(list.toListString())
// String any 查找是否有符合条件的字符
def resultAny = strEach.any {
it.isNumber()
}
println(resultAny)
// every 是否所有的字符都符合条件
def resultEvery = strEach.every {
it.isNumber()
}
println(resultEvery)
// collect 所有的东西都操作, 比如都转化为大写
def listCollection = strEach.collect{
it.toUpperCase()
}
println(listCollection.toListString())
def scriptClosure = {
println(this) // 闭包定义处的类
println(owner) // 闭包定义处的类或者对象
println(delegate) // 任意对象,默认是owner指向的对象
}
scriptClosure.call() // 没有任何区别,在普通类或者对象中也没有任何区别
// 多用于架构设计
def nestClosure = {
def innerClosure = {
println("innerClosure=====================")
println(this) // innerClosure对象
println(owner) // nestClosure对象
println(delegate) // nestClosure对象
}
innerClosure.call()
}
nestClosure.call()
HelloWorld h = new HelloWorld()
def nestClosureD = {
def innerClosureD = {
println("修改delegate=====================")
println(this) // innerClosureD对象
println(owner) // nestClosureD对象
println(delegate) // HelloWorld对象
}
innerClosureD.delegate = h // 修改delegate
innerClosureD.call()
}
nestClosureD.call()
/***
* 闭包的委托策略
*/
class Student{
String name
def desc = {"My name is $name"}
String toString(){
desc.call()
}
}
def student = new Student(name:"wch") // 指定参数,进行构造
println student.toString()
class Teacher{
String name
}
def teacher = new Teacher(name:"derry")
student.desc.delegate = teacher // 代理,是否生效取决于委托策略
student.desc.resolveStrategy = groovy.lang.Closure.DELEGATE_FIRST // 委托策略
println student.toString()