浅析java callback 回调模式
看过spring、hibernate源码的朋友对callback回调模式应该并不陌生,用一句话来概括就是:“if you call me, i will call back”,说白了,就是有相互依赖关系的两个类之间的互相调用,现在看看下面的代码模型:
package com.cuishen.callback;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;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 {return conn.createStatement().executeQuery(sql);}});}public Connection openConnection() throws SQLException {return DriverManager.getConnection("", null);}public void closeConnection(Connection conn) throws SQLException {if(conn != null && !conn.isClosed()) {conn.close();}}}