用方法包装闭包周围的行为

有频繁的行为模式可能导致很多样板代码。通过声明一个以 Closure 为参数的方法,你可以简化程序。例如,检索数据库连接,启动事务,执行工作,然后提交事务或回滚连接(如果发生错误),然后最终关闭连接是一种常见模式:

def withConnection( String url, String user, String pass, Closure closure) {
    Connection conn = null
    try {
        conn = DriverManager.getConnection( url, user, pass )
        closure.call( conn )
        conn.commit()
    } catch (Exception e) {
        log.error( "DB Action failed", e)
        conn.rollback()
    } finally {
        conn?.close()
    }
}

withConnection( DB_PATH, DB_USER, DB_PASS ) { Connection conn ->
    def statement = conn.createStatement()
    def results = statement.executeQuery( 'SELECT * FROM users' )
    // ... more processing ...
}