Design Patterns in Coldfusion (Iterator Pattern)

This is the second article on design patterns in Coldfusion. Part one can be viewed here.

Quick Description
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.

Included Examples:

  • AbstractIterator.cfc
    • Abstract class (with CF8 this could be replaced with <cfinterface>)
  • ArrayIterator.cfc
    • Class to handle iterating over Arrays
  • PersonCollection.cfc
    • Maintains a collection of Persons
  • Person.cfc
    • Basic class
  • Test.cfm
    • Instantiates and displays output forĀ all these CFCs

Links:
Iterator Source Files

Brendan O'Hara's Iterator Article

This entry was posted in Code, Programming, Web Design and tagged , , , . Bookmark the permalink.

2 Responses to Design Patterns in Coldfusion (Iterator Pattern)

  1. Ilya Fedotov says:

    Hello, can you please share your implementation. I think you intended to but the link doesn’t seem to contain the files. Thanks.

  2. Jon Dowdle says:

    @Ilya Thanks for pointing that out. I’ve fixed the link above and here it is again: Iterator Source Files