Monday, 12 October 2015

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


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...