设计模式之迭代器模式

Posted by icoding168 on 2020-03-11 16:26:11

分类: 设计模式  

模式介绍

迭代器模式可以让用户通过特定的接口访问容器中的每一个元素,而不用了解容器底层的具体实现。也就是说只要容器实现了迭代器模式,不管你使用的容器是哪一种,你都可以通过相同的迭代器接口遍历元素。

代码

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() {
         if(index < names.length){
            return true;
         }
         return false;
      }
 
      @Override
      public Object next() {
         if(this.hasNext()){
            return names[index++];
         }
         return 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