Rusty Divine

Live, Love, Learn, Teach

Learning Design Patterns – Iterator Pattern

This week I'll be stepping through the Iterator Pattern in my series on design patterns plucked fromthis book and from examples on the Internet.

What is it?
The Iterator Pattern encapsulates the functionality for stepping through a collection of items. The iterator object implements the stepping; the aggregate itself does not step through its own collection.

The pattern generally has a few of methods like first(), hasNext(), Next(), isDone() in some combination. In some programming languages it is possible to step through an iterator using a For Each item in Aggregate....<code>....Next type of construct.

Where is it used?
Anywhere there is a group of items. An array list is a common example; an iterator would step through the array items until the end of the collection was reached.

But why?
The iterator separates out the functionality of stepping through a group of items into its own class - promoting one-class, one-responsibility design which gives the aggregate only one reason to change itself instead of two. Separating iteration out encapsulates the functionality so that clients can expect predictable results when reviewing a collection, which promotes polymorphism.

OK, and how is it implemented?


//create a concrete aggregate class
public class BookList {
	//create a collection of books
	Hashtable bookItems = new Hashtable();

	public BookList() {
		//constructor code

	public void addBook(Book book) {
		//add the book to the collection
		bookItems.put(book.getISBN(), book);

	//Return an iterator to step through book list.
	//The booklist uses a hashtable to contain its collection,
	//another object (say customerList) may use an arraylist
	//for its collection.  By creating an generic iterator for both
	//concrete aggregate objects, it promotes polymorphism.
	public Iterator createIterator() {
		//iterate through just the book items
		return bookItmes.values().iterator();

//Our booklist uses a hastable, which provides its own iterator method.  
//a more generic collection may need its own iterator created, something
//like this:
public class BookShelfIterator implements Iterator {
	BookShelf[] list;
	int position = 0;

	public BookShelfIterator(BookShelf[] list) {
		this.list = list;

	public Object next() {
		//implementation here

	public boolean hasNext() {
		//implementation here

//the iterator interface for BookShelfIterator:
public interface Iterator {
	boolean hasNext();
	Object newt();
blog comments powered by Disqus