Scala patterns (#5) - the Loan Pattern

按照Scala in action的说法,Scala中的借贷模式(Loan Pattern)相当于Java/C++中的模板方法(Template Method)模式。很遗憾,由于同样的原因,书中所附的引用链接已失效(囧),所以

Loan Pattern as the name suggests would loan a resource to your function. So if you break out the sentence. It would

  • Create a resource which you can use
  • Loan the resources to the function which would use it
  • This function would be passed by the caller
  • The resource would be destroyed

As you would see, the advantages are multifold. First, I am not constrained by the function which can use the loaned resource. I can pass any function that I desire. Second, I am not concerned about the creation, destruction of the resource. The loan function takes care of it.



我认为这种模式也非常符合DRY(Don’t Repeat Yourself)原则,只使用一个函数就可以把相同类型的资源使用代码的重复部分去除,很好。