Iterator模式用于在数据集合中按照顺序遍历集合。

实例程序:将book放置到书架上,并按顺序显示

【图解设计模式】迭代器模式_数据集

 

【图解设计模式】迭代器模式_数据集_02

public interface Aggregate {
    public abstract Iterator iterator();
}
  • 1.
  • 2.
  • 3.
public class Book {
    private String name;
    public Book(String name){
      this.name=name;
    }
    public String getName(){
      return name;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
public class BookShelf implements Aggregate {
   private Book[]books;
   private int last=0;
   public BookShelf(int maxSize){
     this.books=new Book[maxSize];
   }
   public Book getBookAt(int index){
       return books[index];
   }
   public void appendBook(Book book){
       this.books[last]=book;
       last++;
   }
   public int getLength(){
       return last;
   }
   @Override
   public Iterator iterator(){
       return new BookShelfIterator(this);
   }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
public class BookShelfIterator implements Iterator {
  private  BookShelf bookShelf;
  private  int index;
  public BookShelfIterator(BookShelf bookShelf){
    this.bookShelf=bookShelf;
    this.index=0;
  }
  @Override
  public boolean hasNext(){
    if(index<bookShelf.getLength())return true;
    else return false;}
  @Override
  public Object next(){
    Book book = bookShelf.getBookAt(index);
    index++;
    return book;
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
public interface Iterator {
  public abstract boolean hasNext();
  public abstract Object next();
}
  • 1.
  • 2.
  • 3.
  • 4.
public class Main {
  public static void main(String[] args) {
    BookShelf bookShelf=new BookShelf(4);
    bookShelf.appendBook(new Book("a"));
    bookShelf.appendBook(new Book("b"));
    bookShelf.appendBook(new Book("c"));
    Iterator it=bookShelf.iterator();
    while(it.hasNext()){
      Book book =(Book)it.next();
      System.out.println(book.getName());
    }
  }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

【角色说明】

【Iterator】定义按顺序逐个遍历元素的接口(API)

【ConcreteIterator】负责实现Iterator角色所定义的接口。该角色中包含了遍历集合所必需的信息

【Aggregate】负责定义创建Iterator角色的接口。里面定义了iterator方法

【ConcreteAggregate】集合

【图解设计模式】迭代器模式_迭代器模式_03

 引入Iterator后可以将遍历和实现分离开

【图解设计模式】迭代器模式_迭代器模式_04

 这里只使用了Iterator的hasNext方法和next方法,并没有调用BookShelf的方法,就是说不依赖集合的实现。只要具体的集合的iterator方法能正确的返回Iterator实例,不对while做修改也可以。

“可复用”。

“面对接口编程”

【next方法】返回当前元素,并指向下一个元素

【hasNext方法】确认接下来是否可以调用next方法。

【迭代器的种类多种多样】遍历方法可以从前向后,从后向前或者跳跃式遍历

【不需要deleteIterator】java中,没有被使用的对象实例会被自动删除。

手写迭代器模式的注意点 

【图解设计模式】迭代器模式_数据集_05