Groovyノート(二)閉パッケージ
1301 ワード
クローズドパッケージ適用モード:
1.ポリシー・モード:
2.閉パッケージパラメータ:
3.テンプレートメソッドモード:
4.クローズパラメータ
Closure.maximumNumberOfParametersはパラメータの個数を表します
Closure.parameterTypeは閉パケットパラメータタイプを表す
5.クローズパラメータ
owner:閉パッケージを表す外層パッケージがなければ、閉パッケージ自体です.
this:常に閉パッケージの最外層を指すクラス
delegate:閉パッケージ委任クラス
6.クローズコール
a.closure()
b.closure.call()
7.集合クラスへの閉パッケージの適用
any(Closure):存在するかどうかを判断する
every(Closure):それぞれが
collect(Closure):集合全体を遍歴し、Closure内のアルゴリズムによって集合内の要素を置換する
8.閉パケットを戻り値とする
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.parameterTypeは閉パケットパラメータタイプを表す
5.クローズパラメータ
owner:閉パッケージを表す外層パッケージがなければ、閉パッケージ自体です.
this:常に閉パッケージの最外層を指すクラス
delegate:閉パッケージ委任クラス
6.クローズコール
a.closure()
b.closure.call()
7.集合クラスへの閉パッケージの適用
any(Closure):存在するかどうかを判断する
every(Closure):それぞれが
collect(Closure):集合全体を遍歴し、Closure内のアルゴリズムによって集合内の要素を置換する
def result = [1,2,3,4].collect {
i->i**2
}
println result // [1,4,9,16]
8.閉パケットを戻り値とする
def multiply(x) {
return {y->return x*y}
}