Iterator Pattern
Iterator Pattern
Iterator pattern is very commonly used design pattern in Java and .Net programming
environment. This pattern 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.
Implementation
We're going to create a Iterator interface which narrates navigation method and a
Container interface which retruns the iterator . Concrete classes implementing the
Container interface will be responsible to implement Iterator interface and use it
Step 1
Create interfaces.
Iterator.java
https://www.tutorialspoint.com/design_pattern/iterator_pattern.htm 1/3
15/01/24, 11:50 Design Patterns - Iterator Pattern
Container.java
Step 2
Create concrete class implementing the Container interface. This class has inner
class NameIterator implementing the Iterator interface.
NameRepository.java
@Override
public Iterator getIterator() {
return new NameIterator();
}
int index;
@Override
public boolean hasNext() {
@Override
public Object next() {
if(this.hasNext()){
return names[index++];
}
return null;
}
https://www.tutorialspoint.com/design_pattern/iterator_pattern.htm 2/3
15/01/24, 11:50 Design Patterns - Iterator Pattern
}
}
Step 3
Use the NameRepository to get iterator and print names.
IteratorPatternDemo.java
Step 4
Verify the output.
Name : Robert
Name : John
Name : Julie
Name : Lora
https://www.tutorialspoint.com/design_pattern/iterator_pattern.htm 3/3