We tend to think of the iterator pattern as simply a mechanism to access a collection of items in some sort of order. However, the motivation for the iterator pattern goes quite a bit beyond this everyday requirement. It is specifically designed to hide how you decide to structure the collection, but still provide a uniform interface to traverse and access its elements. We will look at a couple of examples where we change how the collection is implemented but keep the client oblivious to the change.
Let’s take a look at the class diagram to determine the relationships between the classes in the iterator pattern.

Gamma et. al. refer to a collection of items as an aggregate. A concrete aggregate implements the IIterableAggregate interface. The IIterableAggregate interface has to define at least one method - called createIterator in this case. Now this is significant because the interface doesn’t specify anything about what data structure should be used to implement your collection of items. The only thing that the client knows about the concrete aggregate is that the createIterator() method will return a concrete iterator.
IIterableAggregate.as
package { public interface IIterableAggregate { function createIterator() : IIterator } }
The concrete iterator is of type IIterator. The IIterator interface defines the basic methods to traverse and access elements of a collection ( I will use the more contemporary term “collection” to refer to a concrete aggregate - not to be confused with the Collection class in AS2 ).
IIterator.as
package { public interface IIterator { function reset() : void function next() : * function hasNext() : Boolean } }
The next() method returns the next element in the collection. Note that it doesn’t specify a return type, allowing the collection to contain any object. The hasNext() method returns a boolean value indicating whether the end of the collection has been reached. The reset() method simply re-positions the index to the starting element.
The two interfaces make the intent of the iterator pattern very clear. The interfaces don’t specify what form or structure the collection takes. The collection can be an Array, Dictionary or a composite like an XML node. However, in combination they do two essential things that enables flexible implementation of collections. First, the Iterator interface provides a uniform way to access elements in a collection. This means that, no matter what structure you use, the collection will be traversed and elements accessed using the next(), hasNext(), and reset() methods. Second, it offloads the iteration and access methods to a separate ConcreteIterator class. Take a look back at the ConcreteAggregate class in the class diagram and note how the createIterator() method is implemented. The returned instance of ConcreteIterator has a parameterized constructor that takes in the instance of the ConcreteAggregate object as an argument. You can think of the iterator as a wrapper around the collection hiding its implementation details. This is what enables the iterator pattern to create extensible and reusable collections.
The Simple List
Let’s develop a minimalist example of an iterable aggregate. The simple list enables clients to create a list of items and access its elements sequentially.
SimpleList.as
package { public class SimpleList implements IIterableAggregate { private var arr : Array; public function SimpleList( ... args ) { arr = new Array(); for ( var i:uint = 0; i < args.length; i++ ) { arr[i] = args[i]; } } public function createIterator() : IIterator { return new SimpleListIterator( arr ); } } }
The SimpleList class implements the IIterableAggregate interface. An Array is used to hold the collection by inserting all arguments passed to the constructor ( elements in the list ). The createIterator() method returns an iterator of type SimpleListIterator. Note how the Array that holds the collection is passed as an argument to the SimpleListIterator constructor.
The concrete aggregate and concrete iterator classes are interdependent as indicated in the class diagram. The dashed arrow from the ConcreteAggregate class to the ConcreteIterator class indicates a dependency; ConcreteAggregate depends on ConcreteIterator to implement the createIterator() method. Conversely, the solid arrow from the ConcreteIterator class to the ConcreteAggregate class indicates a one-way association where ConcreteIterator can access the internal properties of the ConcreteAggregate class.
Now all we have left to do is implement a client that instantiates a SimpleList and iterates through it.
Main.as
package { import flash.display.Sprite; /** * Main Class * @ purpose: Document class for movie */ public class Main extends Sprite { public function Main() { // create an instance of a concrete aggregate var groceryList:SimpleList = new SimpleList( 'bread','butter','eggs' ); // get an iterator for it var itr:IIterator = groceryList.createIterator() // iterate over the agregate while ( itr.hasNext() ) { trace ( itr.next() ); } } } }
The client creates a grocery list, gets an iterator for it, and traces the list. Pretty simple example, but let’s see why the iterator is such an interesting pattern by changing how the collection is implemented.
Changing the implementation
Let’s say that we decide to implement the collection using an XML structure instead of an Array. Assume an hypothetical efficiency provided by the new implementation.
Modified SimpleList.as
package { public class SimpleList implements IIterableAggregate { private var xml : XML; public function SimpleList( ... args ) { xml = <list></list>; for ( var i:uint = 0; i < args.length; i++ ) { xml.appendChild( { args[i] } ); } } public function createIterator() : IIterator { return new XMLListIterator( xml ); } } }
A new type of iterator is needed now since the collection is implemented using a different data structure. An XMLListIterator class is implemented to iterate through an XML list.
XMLListIterator.as
package { public class XMLListIterator implements IIterator { private var xml : XML; private var index : Number; public function XMLListIterator( xmlObject : XML ) { xml = xmlObject; reset(); } public function reset() : void { index = -1; } public function next() : * { return xml.fooditem[ ++index ]; } public function hasNext() : Boolean { return ( index < xml.children().length() - 1 ); } } }
Note that we completely changed the implementation of the concrete aggregate and utilized a new concrete iterator as well. However, the client code will still work as before without requiring any modification.
The iterator pattern allows flexible implementation of collections by not exposing the internal structure of the collection to the client. The iterator pattern is also a good example of how a well defined interface can hide implementation details but expose how modular code can be used.
Why not use for each…in or for…in?
What was that? Total waste of time did you say? Why not use the built-in iterator?
Pretty much all the modern languages have built-in iterators to traverse and access collections; and ActionScript 3 is no exception. This is testament to the utility of design patterns as many of the GoF patterns are natively implemented in AS3. The grocery list could have been created and accessed this way:
var groceryList:Array = new Array( 'bread','butter','eggs' ); for each (var item:* in groceryList) { trace ( item ); }
The collection could have been implemented using any one of the native structures that are enumerable such as XML, Dictionary or even Object and easily accessed using the for each…in looping construct. From a purist’s standpoint, there is a downside as it requires the implementation of the collection to be exposed to the client - since the collection itself is an argument to for each…in.
So, would we ever need to implement an iterator pattern when we have these built-in constructs? Sure! there are collections that are not natively implemented in AS3 such as linked lists, trees, and custom structures that may be required for specific apps. There are also multiple ways of traversing collections. For example, there may be a need to traverse a collection randomly and not in any sequence. A tree structure can be traversed breadth-first as opposed to a depth-first to access its nodes. Implementing an iterator pattern will provide a uniform interface for each unique traversal method.
Look out for a future article on the iterator pattern where we will look at a more functional example that will utilize multiple traversal methods.
Source:
References:
Gamma, Erich; Richard Helm, Ralph Johnson, and John Vlissides (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley.

Great post as usual. I didn’t read it fully but scanned the code.
It probably would be good for folks looking to learn the Iterator to see how you add and remove items from the internal list. That would round out the post so folks can see how solid this pattern can be.
Yeah, looking forward to seeing how a tree would be traversed in this fashion. I’m an AS3 guy and I’m starting to code in Java and I don’t really see too much use for an iterator at this point. Thanks for the pattern!
- TK
Hi John, thanks for the note. I wanted to keep the SimpleList interface really bare to minimize distractions in understanding the core pattern. We are constantly grappling with how minimalist the examples should be without relegating them to irrelevance. It’s very helpful to get feedback on this issue as sometimes we miss the mark. I’m working on a more practical example that my help in showing how “solid” this pattern can be and will post a link here as soon as it’s done.
@TK, you suggestion gave me an idea for an example app - one that uses the iterator pattern to traverse the display list which is a composite tree structure. For example, if you have a complex object in Flash such as a spaceship that has several embedded MovieClips ( engines, fuel tanks etc. ). You can use the iterator pattern to do hit-testing against the embedded components. So, for example, each embedded component can take separate damage when hit by a missile.
Chandima, have you posted the example anywhere? I’m interested in seeing the use behind the Iterator pattern.
- TK
@TK: iteration in trees is handled differently as there are multiple ways of touching all the nodes in a tree. This is called traversing a tree. A Tree can have an iterator, but this will most probably be an implementation of a traversal mechanism like postorder, inorder, preorder or levelorder.
you can check out our site and the as3 opensource package containing data structures in our collections package (including iterators and trees with traversal and iterator mechanisms). Full documentation and source code available, plus unittesting in place.
@chandima: thank you for providing an excellent use of iterators!
The iterator patterns is fully incorporated in our IList interface and List implementations, and features some nice modifications like extended iterators, and unmodifyable iterators.
The bad way would be to make a call to iterator.next(); and then seperately getting the data in iterator.getData(); or the likes.
This allows for infinite loops when forgetting the call to iterator.next(). Your iterator implementation, which is the same as the Java iterator (on which we also based our implementations) is foolproof in this regard
The list (and the whole package actually) is heavily leaning on design patterns and I guess you’ll really like them
Hi Rolf,
Thanks for pointing out the “infinite loop” problem. I did see some implementations out in the wild that had separate methods to advance the pointer and access data but decided to go with the implementation that had the simplest interface — the simpler solution is almost always the right one!!! I do like your collections package where you cast the LinkedList class to the interface you need and use it as a stack, queue etc…. pretty nifty!
Hey your code works great! Hopefuly that you create more codes which are useful like this one. Thx