| ////////////////////////////////////////// |
| |
| Licensed to the Apache Software Foundation (ASF) under one |
| or more contributor license agreements. See the NOTICE file |
| distributed with this work for additional information |
| regarding copyright ownership. The ASF licenses this file |
| to you under the Apache License, Version 2.0 (the |
| "License"); you may not use this file except in compliance |
| with the License. You may obtain a copy of the License at |
| |
| http://www.apache.org/licenses/LICENSE-2.0 |
| |
| Unless required by applicable law or agreed to in writing, |
| software distributed under the License is distributed on an |
| "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| KIND, either express or implied. See the License for the |
| specific language governing permissions and limitations |
| under the License. |
| |
| ////////////////////////////////////////// |
| |
| = Iterator Pattern |
| |
| |
| The http://en.wikipedia.org/wiki/Iterator_pattern[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` and `eachWithIndex` as well as the `for .. in` loop. |
| |
| For example: |
| |
| [source,groovy] |
| ---- |
| include::{projectdir}/src/spec/test/DesignPatternsTest.groovy[tags=iterator_example,indent=0] |
| ---- |
| |
| Results in the output: |
| |
| ---- |
| 1 |
| 2 |
| 3 |
| 4 |
| May=31 |
| Mar=31 |
| Apr=30 |
| java.awt.Color[r=0,g=0,b=0] |
| java.awt.Color[r=255,g=255,b=255] |
| ---- |
| |
| Another example: |
| |
| [source,groovy] |
| ---- |
| include::{projectdir}/src/spec/test/DesignPatternsTest.groovy[tags=iterator_example2,indent=0] |
| ---- |
| |
| Results in: |
| |
| ---- |
| Position 0 contains 'java.awt.Color[r=0,g=0,b=0]' |
| Position 1 contains 'java.awt.Color[r=255,g=255,b=255]' |
| ---- |
| |
| The iterator pattern is also built in to other special operators such as the `eachByte`, `eachFile`, `eachDir`, `eachLine`, `eachObject`, `eachMatch` operators for working with streams, URLs, files, directories and regular expressions matches. |