用方法包裝閉包周圍的行為

有頻繁的行為模式可能導致很多樣板程式碼。通過宣告一個以 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 ...
}