Groovy 设计模式 -- 迭代器模式
Iterator Pattern
http://groovy-lang.org/design-patterns.html#_flyweight_pattern
迭代器模式,允许顺序访问 聚集对象中的中元素, 而不用关心起内部是如何实现的。
groovy有自己的语言内置的闭包操作, 例如 each
The Iterator Pattern allows sequential access to the elements of an aggregate object without exposing its underlying representation.
Groovy has the iterator pattern built right in to many of its closure operators, e.g.
each
andeachWithIndex
as well as thefor .. in
loop.
例子
def printAll(container) { for (item in container) { println item } } def numbers = [ 1,2,3,4 ] def months = [ Mar:31, Apr:30, May:31 ] def colors = [ java.awt.Color.BLACK, java.awt.Color.WHITE ] printAll numbers printAll months printAll colors
colors.eachWithIndex { item, pos -> println "Position $pos contains '$item'" }
出处:http://www.cnblogs.com/lightsong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。