或者,您可以使用模板模式提取连接管道以避免复制/粘贴。基本思想是这样的:
abstract ConnectionTemplate {
private Connection connection = // ...
/**
* Method to be implementad by child classes
*/
public abstract void businessLogicCallback();
/**
* Template method that ensure that mandatory plumbing is executed
*/
public void doBusinessLogic() {
try {
openConnection();
// fetch single result, iterate across resultset, etc
businessLogicCallback();
finally {
closeConnection();
}
}
void openConnection() {
connection.open();
}
void closeConnection() {
if (connection != null) {
connection.close();
}
}
}
现在,实现类可以很简单
class ImportantBusinessClass extends ConnectionTemplate {
@Override
public void businessLogicCallback() {
// do something important
}
}
你像这样使用它
ImportantBusinessClass importantClass = new ImportantBusinessClass();
importantClass.doBusinessLogic(); // opens connection, execute callback and closes connection
Spring 框架在某些地方使用了这种技术,特别是JdbcTemplate处理 SQL、连接、行和域对象之间的映射等。实现细节请参考 GitHub 中的源代码。