Tuesday, July 17, 2012

Behavioral Patterns - 4.Iterator Pattern

Nowadays, most of the applications we are developing are dealing with a huge set of data. These sets of data are termed as collections. A collection is nothing but a group of data.
In order to deal with such type of collections we need some mechanism to traverse over the list. Such mechanism can be termed as an Iterator. They are particularly meant for dealing with a set of data.

An Iterator Design pattern provides a design for an iterator to traverse over and deal with a collection of data.
The iterator should provide methods such as first(),next(),previous(),last(),etc in order to fetch the desired data from the collection.This will ease the process of accessing collection data.

For example, we are going to prepare a Name list for students in a class. This list will be our collection.

We are going to use the Student List for MarkSheet preparation. We need an iterator which can sort and iterate the Student Names alphabetically. One more iterator we need, to sort and traverse the list based on the marks.

Here, we have one collection of Student List for which we need two iterators i.e.StudentNameIterator and MarkListIterator.

Let us design our class as mentioned below,


Code Snippet:--------------
Client:

StudentList studentList=new StudentMarkList();
studentList.add(new Student(...));
...
StudentIterator iterator=studentList.createIterator();
iterator.sort();
iterator.next();
iterator.previous();