考虑下面这个场景:某个操作有预先处理和事后处理两个前后处理,这个操作执行依赖预期行为,预先处理释放出这个操作需要的参数,而事后处理做必要的清理工作。
首先,我们看看如何通过内部类来实现,首先定义一个接口表达需求的行为:
interface OldPerformer {
public void performTask(String id, int status);
}
下面是预先处理Pre-Processing和事后处理Post-processing:
public class PrePostDemo {
static void performTask(String id, OldPerformer performer) {
System.out.println(“Pre-Processing…”);
System.out.println(“Fetching the status for id: ” + id);
int status = 3;//Some status value fetched
performer.performTask(id, status);
System.out.println(“Post-processing…”);
}
}
下面我们看看调用代码PrePostDemo中的main方法:
public static void main(String[] args) {
//内部类需要final
final String outsideOfImpl = "Common Value";
//调用PrePostDemo.performTask方法
performTask("1234", new OldPerformer() {
@Override
public void performTask(String id, int status) {
System.out.println("Finding data based on id...");
System.out.println(outsideOfImpl);
System.out.println("Asserting that the status matches");
}
});
//调用PrePostDemo.performTask方法
performTask("4567", new OldPerformer() {
@Override
public void performTask(String id, int status) {
System.out.println("Finding data based on id...");
System.out.println(outsideOfImpl);
System.out.println("Update status of the data found");
}
});
}
}
输出:
Pre-Processing…
Fetching the status for id: 1234
Finding data based on id…
Common Value
Asserting that the status matches
Post-processing…
Pre-Processing..
Fetching the status for id: 4567
Finding data based on id…
Common Value
Update the status of the data found
Post-processing…
下面我们看看如何使用lambada表达式简单实现:
public class PrePostLambdaDemo {
public static void main(String[] args) {
//不必定义final,但是一旦被lambda使用后不能变化。
String outsideOfImpl = “Common Value”;
doSomeProcessing("123", (String id, int status) -> {
System.out.println("Finding some data based on"+id);
System.out.println(outsideOfImpl);
System.out.println("Assert that the status is "+status );
});
doSomeProcessing("456", (String id, int status) -> {
System.out.print("Finding data based on id: "+id);
System.out.println(outsideOfImpl);
System.out.println("And updating the status: "+status);
});
}
static void doSomeProcessing(String id, Performer performer ){
System.out.println(“Pre-Processing…”);
System.out.println(“Finding status for given id: “+id);
int status = 2;
performer.performTask(id, status);
System.out.println(“Post-processing…”);
}
}
interface Performer{
public void performTask(String id, int status);
}
我们已经看到,区别于内部类,lambda表达式作用域之外的变量不必定义final,但是它是最终的final,也就是说被lambda使用后就不能再赋值变化了。当然,使用lambda表达式比内部类更干净。
转载:http://www.jdon.com/idea/java/java-8-lambdas-simpleapp.html