Iterator Pattern

Iterator Pattern is a behavioral pattern which is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation.

In the following example Iterator interface narrates navigation method and Container interface returns the iterator. Concrete classes implementing the Container interface will be responsible for implementing Iterator interface and use it. IteratorPatternDemo is a demo class that will use NamesRepository, a concrete class implementation to print a Names stored as a collection in NamesRepository.

Iterator Pattern UML Diagram

Step 1 : Create interfaces

public interface Iterator {
boolean hasNext();
Object next();
}

public interface Container {
Iterator getIterator();
}

Step 2 : Create concrete class implementing the Container interface. The class has inner class NameIterator implementing the Iterator interface

public class NameRepository implements Container {
public String names[] = {"Robert", "John", "Julie", "Lora"};

@Override
public Iterator getIterator() {
return new NameIterator();
}

private class NameIterator implements Iterator {
int index;

@Override
public boolean hasNext() {
if (index < names.length) {
return true;
}
return false;
}

@Override
public Object next() {
if (this.hasNext()) {
return names[index++];
}

return null;
}
}
}

Step 3 : Use the NameRepository to get iterator and print names

public class IteratorPatternDemo {
public static void main(String[] args) {
NameRepository nameRepository = new NameRepository();

for (Iterator iter = nameRepository.getIterator(); iter.hasNext();) {
String name = (String)iter.next();
System.out.println("Name : " + name);
}
}
}

The output will be :

Name : Robert
Name : John
Name : Julie
Name : Lora

Leave a Reply

Your email address will not be published. Required fields are marked *