Friday 11 November 2016

Iterator Pattern

Iterator Pattern - Behavioral

Pattern primarily used when you want to traverse a collection in a particular order. It helps to separate the algorithm for traversing the collection from the data structure that represents the collection.
enter image description here
Let’s try to understand with an example. We have a collection that stores all the US Presidents till 2016. Suppose we need to traverse this collection in Chronological Order (in the order in which they held the Presidency) and also in Alphabetical Order(as per the name).
Instead putting all the logic to traverse in the data model (collection), we make use of the Iterator pattern.
interface Iterator {
    String next();
    boolean hasNext();
}
Define, an Interface(Iterator) that provides two methods.
- next() - next name in the collection
- hasNext() - returns true if there are more elements.
We, would be creating two Iterators implementing the above interface, one for each kind of traversal.
interface CollectionInterface {
    Iterator getChronologicalIterator();
    Iterator getAlphabecticalIterator();
}

class Collection implements CollectionInterface {
    String[] listOfUSPresidents = { "George Washington", "John Adams", "Thomas Jefferson", "James Madison",
            "James Monroe", "John Quincy Adams", "Andrew Jackson", "Martin Van Buren ", "William Henry Harrison",
            "John Tyler", "James K. Polk", "Zachary Taylor", "Millard Fillmore", "Franklin Pierce", "James Buchanan",
            "Abraham Lincoln", "Andrew Johnson", "Ulysses S. Grant", "Rutherford B. Hayes", "James A. Garfield",
            "Chester A. Arthur", "Grover Cleveland", "Benjamin Harrison", "Grover Cleveland", "William McKinley",
            "Theodore Roosevelt", "William Howard Taft", "Woodrow Wilson", "Warren G. Harding", "Calvin Coolidge",
            "Herbert Hoover", "Franklin Roosevelt", "Harry S. Truman", "Dwight D. Eisenhower", "John F. Kennedy",
            "Lyndon B. Johnson", "Richard M. Nixon", "Gerald Ford", "Jimmy Carter", "Ronald Reagan", "George Bush",
            "Bill Clinton", "George W. Bush", "Barack Obama", };

    @Override
    public Iterator getChronologicalIterator() {

        return new Iterator(){
            int index =0;
            @Override
            public String next() {
                 if(this.hasNext()){
                        return listOfUSPresidents[index++];
                     }
                     return null;
            }

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

        };
    }


    @Override
    public Iterator getAlphabecticalIterator() {

        return new Iterator(){
            int index =0;
            String []sortedList = getSortedList(listOfUSPresidents);

            @Override
            public String next() {
                 if(this.hasNext()){
                        return sortedList[index++];
                     }
                     return null;
            }

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

            String [] getSortedList(String []names){
                String [] sortedList = names;
                Arrays.sort(sortedList);
                return sortedList;
            }

        };
    }
}
Collection stores the list of Presidents, We have two implementations of the Iterators, one representing the chronological order(same as the model), the other iterator internally sorts the list of names to provide alphabetically order.

Key Points

  1. Traverse a collection of Objects(Model) without proliferating the traversing logic inside the collection object.
  2. Provide multiple strategies/algorithms for traversing the same collection/model.
public class IteratorDemo {

    public static void main(String[] args) {
        Collection collection = new Collection();
        // Chronological Iterator
        System.out.println("List of Presidents in Chronolgical Order");
        Iterator chronoIterator = collection.getChronologicalIterator();
        while (chronoIterator.hasNext()) {
            System.out.println(chronoIterator.next());
        }

        // Alphabetical Iterator
        System.out.println("List of Presidents in Aphabetical Order");
        Iterator alhabaItetrator = collection.getAlphabecticalIterator();
        while (alhabaItetrator.hasNext()) {
            System.out.println(alhabaItetrator.next());
        }
    }

}

Output : List of US Presidents

List of Presidents in Chronolgical Order
George Washington
John Adams
Thomas Jefferson
James Madison
James Monroe
John Quincy Adams
Andrew Jackson
Martin Van Buren 
William Henry Harrison
John Tyler
James K. Polk
Zachary Taylor
Millard Fillmore
Franklin Pierce
James Buchanan
Abraham Lincoln
Andrew Johnson
Ulysses S. Grant
Rutherford B. Hayes
James A. Garfield
Chester A. Arthur
Grover Cleveland
Benjamin Harrison
Grover Cleveland
William McKinley
Theodore Roosevelt
William Howard Taft
Woodrow Wilson
Warren G. Harding
Calvin Coolidge
Herbert Hoover
Franklin Roosevelt
Harry S. Truman
Dwight D. Eisenhower
John F. Kennedy
Lyndon B. Johnson
Richard M. Nixon
Gerald Ford
Jimmy Carter
Ronald Reagan
George Bush
Bill Clinton
George W. Bush
Barack Obama

List of Presidents in Aphabetical Order
Abraham Lincoln
Andrew Jackson
Andrew Johnson
Barack Obama
Benjamin Harrison
Bill Clinton
Calvin Coolidge
Chester A. Arthur
Dwight D. Eisenhower
Franklin Pierce
Franklin Roosevelt
George Bush
George W. Bush
George Washington
Gerald Ford
Grover Cleveland
Grover Cleveland
Harry S. Truman
Herbert Hoover
James A. Garfield
James Buchanan
James K. Polk
James Madison
James Monroe
Jimmy Carter
John Adams
John F. Kennedy
John Quincy Adams
John Tyler
Lyndon B. Johnson
Martin Van Buren 
Millard Fillmore
Richard M. Nixon
Ronald Reagan
Rutherford B. Hayes
Theodore Roosevelt
Thomas Jefferson
Ulysses S. Grant
Warren G. Harding
William Henry Harrison
William Howard Taft
William McKinley
Woodrow Wilson
Zachary Taylor
Written with StackEdit.

No comments:

Post a Comment