[Jakarta Commons筆記](méi) Commons Collections - Closure組
Posted on 2005-08-06 12:31 laogao 閱讀(2154) 評(píng)論(1) 編輯 收藏 所屬分類: On Java接下來(lái)看Closure組。
Closure
ChainedClosure
IfClosure
WhileClosure
ClosureUtils
Closure這一組接口和類提供一個(gè)操作對(duì)象的execute方法,為我們?cè)谔幚硪幌盗袑?duì)象時(shí)可以將處理邏輯分離出來(lái)。理論上講,使用Transformer也可以達(dá)到類似的效果,只要輸出對(duì)象和輸入對(duì)象是同一個(gè)對(duì)象就好,但是Closure接口定義的execute方法返回void,并且從效果和功能區(qū)分上,Closure可以更好的詮釋對(duì)象處理或執(zhí)行的意思。而事實(shí)上,ClosureUtils中也提供了一個(gè)asClosure方法包裝一個(gè)現(xiàn)成的Transformer。
沿用前面的Emploee類,我們來(lái)給一組員工漲工資:
package sean.study.commons.collections;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import org.apache.commons.collections.Closure;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
public class ClosureUsage {
public static void main(String[] args) {
demoClosureUsage();
}
public static void demoClosureUsage() {
System.out.println(StringUtils.center(" demoClosureUsage ", 40, "="));
// data setup
Employee[] employees = new Employee[] {
new Employee("Tony", 26, new Date(), "E4", 2000),
new Employee("Michelle", 24, new Date(), "E4", 2000),
new Employee("Jack", 28, new Date(), "E5", 3000)
};
Collection empColl = Arrays.asList(employees);
printColl("Before salary increase:", empColl);
// closure setup
Closure salaryIncreaseClosure = new Closure() {
public void execute(Object obj) {
Employee emp = (Employee) obj;
emp.setSalary(emp.getSalary() * 1.20);
}
};
// salary increase
CollectionUtils.forAllDo(empColl, salaryIncreaseClosure);
printColl("After salary increase:", empColl);
System.out.println(StringUtils.repeat("=", 40));
}
public static void printColl(String label, Collection c) {
if (StringUtils.isNotBlank(label)) {
System.out.println(label);
}
Iterator iter = c.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}
以下是運(yùn)行結(jié)果:
=========== demoClosureUsage ===========
Before salary increase:
Employee[name=Tony,age=26,dateJoined=
Employee[name=Michelle,age=24,dateJoined=
Employee[name=Jack,age=28,dateJoined=
After salary increase:
Employee[name=Tony,age=26,dateJoined=
Employee[name=Michelle,age=24,dateJoined=
Employee[name=Jack,age=28,dateJoined=
========================================
我這里舉的是一個(gè)相對(duì)簡(jiǎn)單的例子,在Closure這一組還有一些很方便的類,如ChainedClosure可以包裝一組Closure作為整體執(zhí)行;IfClosure在創(chuàng)建時(shí)需要提供給它一個(gè)Predicate和兩個(gè)Closure,執(zhí)行時(shí)先做Predicate判定再?zèng)Q定執(zhí)行哪一個(gè)Closure;SwitchClosure跟SwitchTransformer類似,根據(jù)創(chuàng)建時(shí)傳入的Predicate組和Closure組對(duì)應(yīng)執(zhí)行;WhileClosure則根據(jù)創(chuàng)建時(shí)傳入的Predicate做判斷,如果為true則執(zhí)行Closure,直到Predicate返回false;等等。
具體用法請(qǐng)參考Javadoc。