What is the “Execute Around” idiom?

后端 未结 8 1427
不思量自难忘°
不思量自难忘° 2020-11-22 12:39

What is this \"Execute Around\" idiom (or similar) I\'ve been hearing about? Why might I use it, and why might I not want to use it?

8条回答
  •  时光说笑
    2020-11-22 13:25

    If you want groovy idioms, here it is:

    //-- the target class
    class Resource { 
        def open () { // sensitive operation }
        def close () { // sensitive operation }
        //-- target method
        def doWork() { println "working";} }
    
    //-- the execute around code
    def static use (closure) {
        def res = new Resource();
        try { 
            res.open();
            closure(res)
        } finally {
            res.close();
        }
    }
    
    //-- using the code
    Resource.use { res -> res.doWork(); }
    

提交回复
热议问题