演化架构与紧急设计: 组合方法和 SLAP
2009-11-05 00:00:00 来源:WEB开发网这很有意思。是否还能把更多的方法从子类提升到通用的父类中?如果看一下 清单 2 中的 populate() 方法本身,可以看出它与 PartDb 类的连接点是 getDatabaseConnection()、createResultSet() 和 addPartToListFromResultSet() 方法。前两个方法已经转移到父类中了。如果对 addPartToListFromResultSet() 方法进行抽象(并使用适当的更通用的名称),就可以把整个 populate() 方法放到父类中,见清单 4:
清单 4. BoundaryBase 类abstract public class BoundaryBase {
private static final String DRIVER_CLASS =
"com.mysql.jdbc.Driver";
private static final String DB_URL =
"jdbc:mysql://localhost/orderentry";
protected Connection getDatabaseConnection() throws ClassNotFoundException,
SQLException {
Connection c;
Class.forName(DRIVER_CLASS);
c = DriverManager.getConnection(DB_URL, "webuser", "webpass");
return c;
}
abstract protected String getSqlForEntity();
protected ResultSet createResultSet(Connection c) throws SQLException {
Statement stmt = c.createStatement();
return stmt.executeQuery(getSqlForEntity());
}
abstract protected void addEntityToListFromResultSet(ResultSet rs)
throws SQLException;
public void populate() throws Exception {
Connection c = null;
try {
c = getDatabaseConnection();
ResultSet rs = createResultSet(c);
while (rs.next())
addEntityToListFromResultSet(rs);
} finally {
c.close();
}
}
}
更多精彩
赞助商链接