Groovy 设计模式 -- 借贷
设计模式 -- Groovy
2023-09-27 14:28:37 时间
借贷模式
http://groovy-lang.org/design-patterns.html#_loan_my_resource_pattern
The Loan my Resource pattern ensures that a resource is deterministically disposed of once it goes out of scope.
This pattern is built in to many Groovy helper methods. You should consider using it yourself if you need to work with resources in ways beyond what Groovy supports.
模式反例
def reader = f.newReader() reader.splitEachLine(' ') { wordList -> println wordList } reader.close() // => // [ "Mon", "Jun", "18", "22:38:17", "EST", "2007" ] // [ "RunPattern" ]
模式正例
def withListOfWordsForEachLine(File f, Closure c) { def r = f.newReader() try { r.splitEachLine(' ', c) } finally { r?.close() } }
Now, we can re-write our code as follows:
withListOfWordsForEachLine(f) { wordList -> println wordList } // => // [ "Mon", "Jun", "18", "22:38:17", "EST", "2007" ] // [ "RunPattern" ]
This is much simpler and has removed the explicit close()
. This is now catered for in one spot so we can apply the appropriate level of testing or reviewing in just one spot to be sure we have no problems.
相关文章
- java设计模式--行为型模式--备忘录模式
- java设计模式--行为型模式--迭代模式
- 设计模式(三)-- 适配器模式(Adapter)
- 设计模式只看不练可不行,写个上传解耦库练练手(下)
- 开源DDD设计模式框架YMNNetCoreFrameWork第一篇
- js--设计模式--适配器模式
- 设计模式-工厂方法(Demo)
- 《大话设计模式 Java溢彩加强版》相关主题
- 跟JBPM学习设计模式之简单工厂模式
- Android 常用设计模式(二) -- 单例模式(详解)
- 读书--大话设计模式阅读完毕
- C#设计模式系列:装饰模式(Decorator)
- Groovy 设计模式 -- 迭代器模式
- Groovy 设计模式 -- 装饰器模式
- PHP设计模式——代理模式
- 模板方法设计模式(TemplateMethod)
- 浅谈设计模式-构建者模式
- 大战设计模式【18】—— 职责链模式
- 设计模式之创建型模式
- 【设计模式系列】--原型模式