2007 |
Section 4, Chapter 3 |
Iterator Pattern
Concept
Iterators allow sequential access of elements in a collection of objects without exposing its underlying code.
Use
If you have a list object and you wish to move through each element in the list sequentially and maintain your current place in the list, an iterator seems appropriate.
Design
- Aggregate: a collection or aggregate object of some type whose elements we wish to iterate through.
- Iterator: a tool to move through the aggregate elements and keep track of the progress.
Illustration
class List
{
private ArrayList _listItems = new ArrayList();
public Iterator CreateIterator()
{
return new Iterator(this);
}
public int Count
{
get{ return _listItems.Count; }
}
public void Append(object item)
{
_listItems.Add(item);
}
public void Remove(object item)
{
_listItems.Remove(item);
}
public void RemoveAt(int index)
{
_listItems.RemoveAt(index);
}
public object this[int index]
{
get{ return _listItems[index]; }
set{ _listItems[index] = value; }
}
}
class Iterator
{
private List _collection;
private int _currentIndex = 0;
private int _stepCount = 1;
public Iterator(List collection)
{
this._collection = collection;
}
public int Step
{
get{ return _stepCount; }
set{ _stepCount = value; }
}
public object First()
{
_currentIndex = 0;
return _collection[_currentIndex];
}
public object Next()
{
_currentIndex += _stepCount;
if(!IsDone())
return _collection[_currentIndex];
else
return null;
}
public object Last()
{
_currentIndex = _collection.Count - 1;
return _collection[_currentIndex];
}
public object Current()
{
return _collection[_currentIndex];
}
public bool IsDone()
{
return _currentIndex >= _collection.Count ? true : false ;
}
}
Iterator skipIterator = list.CreateIterator();
skipIterator.Step = 3;
for(object item = skipIterator.First(); !skipIterator.IsDone(); item = skipIterator.Next())