This is the second article on design patterns in Coldfusion. Part one can be viewed here.
The iterator provides a single way to loop over a collection of elements without having to worry which type of collection (list, struct, array, query) it is. The interface for an iterator is quite simple with the main methods being hasNext() and next(). hasNext() returns true or false depending on if there are additional elements, while next() returns the next elements.
Speaking of collections, there is a collection class included with the source files. Using a class to contain the collection is preferable because it abstracts the data storage method for groups of objects, which lets us use the iterator class seamlessly. I find being ignorant of the underlying data type gives much more flexibility. I plan on going to more detail with the AbstractCollection and the implementation more in a future post.
Most of the code is taken from Brendan O'Hara's article, with the largest exception being the addAll() method in my PersonCollection.cfc. So again, many thanks to him for his wonderful post on CFDJ.
- Abstract class (with CF8 this could be replaced with <cfinterface>)
- Class to handle iterating over Arrays
- Maintains a collection of Persons
- Basic class
- Instantiates and displays output for all these CFCs
Iterator Source Files
Brendan O'Hara's Iterator Article