Wednesday, June 15, 2022

Design Pattern: Iterator Pattern

Chapters

Iterator Pattern

Iterator pattern is a design pattern used to access and traverse a collection such as a list. This pattern decouples algorithms from containers.

Some programming languages have built-in iterator in them. Those built-in and general-purpose iterators are can solve most problems and I recommend using them. For example, java provides Iterator interface that is used to traverse collections such as ArrayList and others.

This diagram shows a structure of an iterator pattern Diagram
Courtesy of Wikipedia

This example demonstrates iterator pattern. Take note that this example is just a mere demonstration and not recommended to be reproduced in production.
import java.util.List;
import java.util.ArrayList;

public class ClientCode{

  public static void main(String[] args){
    Aggregate collection = 
    new ConcreteAggregate();
    
    collection.add("A");
    collection.add("B");
    collection.add("C");
    collection.add("D");
    collection.add("E");
    
    SampleIterator iterator =
    collection.createIterator();
    
    while(iterator.hasNext())
      System.out.println(iterator.next());
  }
}

/*
Assume classes below are in different package
and they're all public except for 
ConcreteIterator class
*/
interface Aggregate{

  void add(String element);
  SampleIterator createIterator();
}

class ConcreteAggregate implements Aggregate{
  private List<String> list;
  private SampleIterator iterator;
  
  ConcreteAggregate(){
    list = new ArrayList<>();
  }
  
  @Override
  public void add(String element){
    list.add(element);
  }
  
  @Override
  public SampleIterator createIterator(){
    return new ConcreteIterator(list);
  }
}

interface SampleIterator{

  String next();
  boolean hasNext();
}

class ConcreteIterator implements SampleIterator{
  private List<String> list;
  private int pointer;
  
  ConcreteIterator(List<String> list){
    this.list = list;
  }
  
  @Override
  public String next(){
    if(pointer >= list.size())
      throw new ArrayIndexOutOfBoundsException();
    String result = list.get(pointer);
    pointer++;
    return result;
  }
  
  @Override
  public boolean hasNext(){
    if(pointer >= list.size())
      return false;
    else
      return true;
  }
  
}

Result
A
B
C
D
E

No comments:

Post a Comment