本文转载自:http://totty.iteye.com/blog/116192
看Spring源码中在sql操作处用回调函数觉得大为精妙,自己也写了一个demo,记录下来,以便以后可以参考。
TestCallBack.java 代码
package per;
public interface TestCallBack {
Object doSomeThing(TestExecute executor) ;
}
TestExecute.java 代码
package per;
public class TestExecute {
public Object doExecute1() {
System.out.println("in TestExecute doExecute1()");
System.out.println(" can do sql operation1");
return "";
}
public Object doExecute2() {
System.out.println("in TestExecute doExecute2()");
System.out.println(" can do sql operation2");
return "";
}
}
TestTemplate.java 代码
package per;
public class TestTemplate {
public Object execute(TestCallBack action) {
try {
System.out.println("in TestTemplate execute()");
System.out.println(" can create sql connection");
TestExecute executor = new TestExecute();
action.doSomeThing(executor);
return "";
} finally {
System.out.println("in TestTemplate finally");
System.out.println(" can close sql connection");
}
}
public Object doThing1() {
System.out.println("in TestTemplate doThing1()");
Object ob = execute(new TestCallBack() {
public Object doSomeThing(TestExecute executor) {
System.out.println("in TestTemplate doThing()'s callback method");
executor.doExecute1();
return "";
}
});
return ob;
}
public Object doThing2() {
System.out.println("in TestTemplate doThing2()");
Object ob = execute(new TestCallBack() {
public Object doSomeThing(TestExecute executor) {
System.out.println("in TestTemplate doThing()'s callback method");
executor.doExecute2();
return "";
}
});
return ob;
}
}
TestRun.java 代码
package per;
public class TestRun {
public static void main(String[] args) {
new TestTemplate().doThing1();
new TestTemplate().doThing2();
}
}
输出结果为:
in TestTemplate doThing1()
in TestTemplate execute()
can create sql connection
in TestTemplate doThing()'s callback method
in TestExecute doExecute1()
can do sql operation1
in TestTemplate finally
can close sql connection
in TestTemplate doThing2()
in TestTemplate execute()
can create sql connection
in TestTemplate doThing()'s callback method
in TestExecute doExecute2()
can do sql operation2
in TestTemplate finally
can close sql connection
用回调函数,我们可以把创建数据库连接和数据库关闭操作单独出去,而不用在每一次数据库操作时都要先建立连接,再进行数据库操作,操作完后还要关闭连接,而且数据库操作还得放在try catch finally当中。
Excellent, Rod Johnson !