zwvista

导航

设计模式学习笔记(1)Iterator

Iterator 模式

Iterator Pattern

public interface Iterator {
   public boolean hasNext();
   public Object next();
}
public interface Container {
   public Iterator getIterator();
}
public class NameRepository implements Container {
   public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};

   @Override
   public Iterator getIterator() {
      return new NameIterator();
   }

   private class NameIterator implements Iterator {

      int index;

      @Override
      public boolean hasNext() {
        return index < names.length;
      }

      @Override
      public Object next() {
        return hasNext() ? names[index++] : null;
      }		
   }
}
public class IteratorPatternDemo {
	
   public static void main(String[] args) {
      NameRepository namesRepository = new NameRepository();

      for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){
         String name = (String)iter.next();
         System.out.println("Name : " + name);
      } 	
   }
}
Name : Robert
Name : John
Name : Julie
Name : Lora

posted on 2017-12-14 22:53  zwvista  阅读(151)  评论(0编辑  收藏  举报