— Forest and the Trees

Iterator Pattern Files

I finally cleaned up the files I showed for my Iterator presentation a few weeks ago. Here’s the code. All of these examples are basically Hello Worlds. They should be pretty easy to understand, but, they’re not that exciting.

The main class is IteratorTalkMain. Take a look at the init() method and you can comment in/out various methods that demonstrate different aspects of iterator.

The code demonstrates the following:
1. Simple iterator.
2. Iterating on an interval without having to add much to your main class.
3. Iterate using the remove() method. (Earlier methods shown are hasNext() and next())
4. Iterating over a hash array. Because your iterator class is external to the class that is calling the iteration, the class that calls the iteration is able to treat a hash identically to an array.
5. Using different iterators to traverse the same data. This example filters out strings that do not have a minimum length.
6. Internal iteration. For internal iterations, you pass a method to the class that holds the data, the data class traverses over its data and modifies the data using the method passed. I am not sure if I implemented this correctly. In general, it seems that internal iterators are frowned upon (at least in the GoF book).
7. Composite Iterator. This is the most complex. It shows how to iterate over a data structure that uses the Composite Pattern. In Composite, both nodes and leaves are treated identically. The iterator is recursive. There is one weird glitch in the CompositeIterator class. Everything works, but, I ended up having the iterator creation increment by 2 when I used push (which froze the player) – to fix it I added a klugey length check. If you want to take a look – look for the ‘wtf’ comment.

Most of this code was based on code from Heads Up Design Patterns, which is a great book. I also read the Iterator chapter in the Gang of Four book.

I am not a design patterns expert. If you find errors in this code, let me know.

In addition to the code, there is a swf of the presentation – basically text slides.

This code is open source. Use for whatever you want.

0 comments
Submit comment

Cristal casino: сейчас Фортуна - в вашей команде. Время на триумфальную победу!