java 回调模式 (部分转载,部分原创)

“if you call me, i will call back”,说白了,就是有相互依赖关系的两个类之间的互相调用

package callBack;

publicclassContextimplementsA.Callback{

privateAa;

publicvoidbegin(){
System.out.println("begin...");
}

publicvoidend(){
System.out.println("end...");
}

publicContext(){
this.a=newA(this);
}

publicvoiddoSomething(){
this.a.doIt();
}

publicstaticvoidmain(Stringargs[]){
newContext().doSomething();
}
}

package callBack

publicclassA{

privatefinalCallbackcallback;

publicstaticinterfaceCallback{
publicvoidbegin();
publicvoidend();
}
publicA(Callbackcallback){
this.callback=callback;
}
publicvoiddoIt(){
callback.begin();
System.out.println("dosomething...");
callback.end();
}
}

上面的代码模型其原型是出自hibernate里的org.hibernate.jdbc.JDBCContext 和 org.hibernate.jdbc.ConnectionManager两个类,从上面的模型不难看出:Context类实现了A类的Callback接口,在Context类的构造器里将自己注入了A类,在Context类里调用A类的doIt()方法,这时就是:you call me;在doIt()方法体里调用了Context类的begin()和end()方法,这时就是:i call back。Context类 和 A类相互依赖,互相调用
在hibernate的源代码里大量使用了上面的callback回调模型,又如:org.hibernate.jdbc.JDBCContext 和 org.hibernate.impl.SessionImpl等等,可以自己去看源代码,这里不再赘述。

当然上面提到的模型中的两个类也可以写在同一个类里面,定义的Callback接口可以用内部匿名类来实现,比如下面的一个简单的dao实现:

package callBack;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;

public class Dao {
private interface Callback {
Object doIt(Connection conn) throws SQLException;
}
private Object execute(Callback callback) throws SQLException {
Connection conn = openConnection(); // 开启数据库连接
try { return callback.doIt(conn); } // 执行具体操作并返回操作结果
finally { closeConnection(conn); } // 关闭数据库连接
}

public Object sqlQuery(final String sql) throws SQLException {
return execute(
new Callback() {
public Object doIt(Connection conn) throws SQLException {
ResultSet rs=conn.createStatement().executeQuery(sql);
while(rs.next()){
System.out.print(rs.getInt("id")+"\t");
System.out.print(rs.getString("userName")+"\t");
System.out.print(rs.getString("email")+"\t");
System.out.print(rs.getString("passWord")+"\t");
System.out.print(rs.getString("address")+"\t");
System.out.print(rs.getString("sex")+"\t");
System.out.print(rs.getString("work")+"\t");
System.out.println();
}
return rs;
}
}
);
}

public Connection openConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/blog", "root", "root");
}
public void closeConnection(Connection conn) throws SQLException {
if(conn != null && !conn.isClosed()) {
conn.close();
}
}

public static void main(String[] args){
Dao dao=new Dao();
try{
String sql="select * from user";
Class.forName("com.mysql.jdbc.Driver");
dao.sqlQuery(sql);

}catch(Exception e){
e.printStackTrace();
}
}
}
用这种回调模式方便的把openConnection()和closeConnection()做了切片,从代码中剥离出来,使代码复用性更高,也更简洁



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值