Monday, 8 January 2018

Design Patterns | Iterator pattern or Cursor

Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.
package designpattern.iterator;
public interface Iterator {
      public boolean hasNext();
      public Object next();
}

public interface IContainer {
      public Iterator getIterator();
}

public class Mp3Player implements IContainer {
      private int size;
      private int index;
      private Object songsList[];
     
      public Mp3Player(int size) {
            songsList = new Object[size];
            this.size = size;
            index = 0;
      }
     
      @Override
      public Iterator getIterator() {
            return new SongsIterator();
      }

      private class SongsIterator implements Iterator {
            int index;

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

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

      public void addName(Object string) {
            if(index<size) {
                  songsList[index] = string;
            }
            index++;
      }
}

public class IteratorPatternTest {

      public static void main(String[] args) {
            Mp3Player mp3Player = new Mp3Player(2);
            mp3Player.addName("Is it love!");
            mp3Player.addName("Feel me");
           
            Iterator iter = mp3Player.getIterator();
            while(iter.hasNext()) {
                  String name = (String) iter.next();
                  System.out.println("Song: " + name);
            }
      }
}

Output:
Song: Is it love!
Song: Feel me

The examples in Java's core libraries
All implementations of java.util.Iterator(thus among others also java.util.Scanner).
All implementations of java.util.Enumeration.

2 comments:

Related Posts Plugin for WordPress, Blogger...