Iterator Design Pattern in Java
Type : Behavioral Design Pattern
Summary
Iterator allows sequential traversal through a data structure without exposing its internal details.
Iterator design pattern provides a standard well versed methods to traverse collection. Client can use the Iterator to traverse the data structure without knowing its internal details.
Advantages
Iterator provides standard API that the client can use to navigate though the Data structure.
It helps in hiding the internal data of the Data Structure and provide a mechanism to access the information that is designed to be accessible through Iterator.
Details
Iterator design pattern is very useful in programming languages like java which provides iterator for the Collections. If we want to iterate though an aggregation of objects, we have to come up with some mechanism. Iterator design pattern helps with navigating though the collection.
Example
Say we have a Book object which contains list of Chapter objects and each Chapter contains list of pages. We want to navigate though the pages. May be we want to navigate pages chapter wise or book as a whole. We can write Iterators for encapsulating the logic behind the need.
BookPageIterator is the iterator which provides a mechanism to traverse the book from start to end.
BookPageIterator is the iterator which provides a mechanism to traverse the book from start to end.
Class Diagram
Sample Code
public class Book {
List chapter;
public Book(List chapter) {
this.chapter = chapter;
}
public CustomBookIterator getIterator() {
return new BookPageIterator(chapter, true);
}
}
public class BookChapter {
List pages;
}
public class BookPage {
private String content;
}
// iterator interface
public interface CustomBookIterator {
public BookPage nextPage();
public boolean isLastBookPage();
}
// concrete iterator
public class BookPageIterator implements CustomBookIterator {
private List bookPageList;
private int position;
public BookPageIterator(List chapter, boolean s) {
this.bookPageList = new ArrayList();
for (BookChapter chap : chapter) {
bookPageList.addAll(chap.getPages());
}
}
public BookPageIterator(List pages) {
this.bookPageList = pages;
}
@Override
public BookPage nextPage() {
BookPage nextPage = null;
if (position < bookPageList.size() - 1) {
nextPage = bookPageList.get(position);
position++;
}
return nextPage;
}
@Override
public boolean isLastBookPage() {
boolean ret = false;
ret = (position) == bookPageList.size() - 1;
return ret;
}
}
Comments
Post a Comment