Iterator模式用于在数据集合中按照顺序遍历集合。英语单词Iterate有重复做某件事情的意思。也叫做“迭代器”。
登场角色
-
Iterator(迭代器)
该角色负责定义按顺序逐个遍历元素的接口(API)。在下图中由Iterator接口扮演这个角色,它定义了hasNext和next两个方法。
-
Iterator接口
public interface Iterator{
public abstract boolean hasNext();
public abstract Object next();
}
-
ConcreteIterator(具体的迭代器)
该角色负责实现Iterator角色所定义的接口(API)。在示例中,由BookShelfIterator类扮演这个角色。该角色包含了遍历集合所必需的信息。
-
BookShelfIterator类
public class BookShelfIterator implments Iterator{
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf = bookShelf;
this.index = 0;
}
public boolean hasNext(){
if(index<bookShelf.getLength()) {
return true;
}else{
return false;
}
}
public Object next(){
Book book = bookShelf.getBookAt(index);
index++;
return book;
}
}
-
Aggregate(集合)
该角色负责定义创建Iterator角色的接口(API)。这个接口是一个方法,会创建出“按顺序访问保存在我内部元素的人”。在示例程序中由Aggregate接口扮演这个角色,它里面定义了iterator方法。
-
Aggregate接口
public interface Aggregate{
public abstract Iterator iterator();
}
-
ConcreteAggregate(具体的集合)
该角色负责实现Aggregate角色所定义的接口(API)。它会创建具体的Iterator角色,在示例的程序中,由BookShelf类 扮演这个角色。
-
BookShelf类
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;
}
public Iterator iterator(){
return new BookShelfIterator(this);
}
}
![](https://img.haomeiwen.com/i14944576/b6c7fcb99e200bb1.png)
网友评论