scala 借贷模式(loan pattern)通用实现

来源:互联网 发布:怎么检查网络是否连接 编辑:程序博客网 时间:2024/05/16 19:57
import scala.language.reflectiveCallsimport util.control.Exception._import scala.concurrent.{ ExecutionContext, Future }object LoanPattern extends LoanPattern/** * Loan pattern implementation */trait LoanPattern {  type Closable = { def close() }  def using[R <: Closable, A](resource: R)(f: R => A): A = {    try {      f(resource)    } finally {      ignoring(classOf[Throwable]) apply {        resource.close()      }    }  }  /**   * Guarantees a Closeable resource will be closed after being passed to a block that takes   * the resource as a parameter and returns a Future.   */  def futureUsing[R <: Closable, A](resource: R)(f: R => Future[A])(implicit ec: ExecutionContext): Future[A] = {    f(resource) andThen { case _ => resource.close() } // close no matter what  }}


调用:

LoanPattern.using(resource)(f)
比如resource可以是jdbc connection或者是file等等资源,在使用完之后,会自动调用close方法关闭资源。

0 0
原创粉丝点击