我想制作一个SqliteHelper,它将强制任何用户在执行查询后正确关闭连接。
有没有一种模式可以确保这一点?
您可以尝试制作需要将用户操作作为lambda表达式或方法引用提供的辅助方法。我不确定您是如何连接到SQLite的,所以我将在我的示例中使用JDBC类:
public static void doAction(Consumer<Connection> userAction) {
try (Connection conn = /* logic to create connection */) {
userAction.accept(conn);
}
// Connection automatically closed due to try-with-resources
}
用户可以执行以下操作:
SqliteHelper.doAction(conn -> {
// Logic that uses connection
});
这种方法的一个问题是Consumer
要求您在lambda主体中捕获异常。如果这不是你想要的,你可以定义自己的功能接口,允许异常:
@FunctionalInterface
public interface SqliteOperation {
void perform(Connection connection) throws SQLException;
}
doAction
方法需要稍微调整一下:
public static void doAction(Consumer<Connection> userAction) {
try (Connection conn = /* logic to create connection */) {
userAction.accept(conn);
} catch (SQLException e) {
// Log the error, wrap it in another exception, just don't ignore it
}
// Connection automatically closed due to try-with-resources
}