Iterator迭代器的定義:迭代器(Iterator)模式,又叫做游標(Cursor)模式。GOF給出的定義為:提供一種方法訪問一個容器(container)對象中各個元素,而又不需暴露該對象的內部細節。 參考下面的實例來理解迭代器。
接口Iterator集合迭代器
/**
* @Acthor:
* @ClassName:Iterator
* @Description:循環遍歷
*/
public interface Iterator {
boolean hasNext();
Object next();
}
接口Aggregate生成集合迭代器
/**
* @Acthor:
* @ClassName:Aggregate
* @Description:該接口生成遍歷集合的迭代器
*/
public interface Aggregate {
Iterator iterator() ;
}
遍歷集合對象book
/**
* @Acthor:
* @ClassName:book
* @Description:遍歷對象是書
*/
public class book {
private String name;
public book(String name){
this.name = name ;
}
public String getName() {
return name;
}
}
創建放書的容器書柜BookShelf
/**
* @Acthor:
* @ClassName:BookShelf
* @Description:書柜是放書的容器
*/
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 books){
this.books[last] = books ;
last++ ;
}
public int getLength(){
return last ;
}
@Override
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
遍歷書柜(容器)中的書
/**
* @Acthor:
* @ClassName:
* @Description:遍歷書柜容器的書
*/
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 b = bookShelf.getBookAt(index);
index++ ;
return b;
}
}
測試代碼
import java.awt.print.Book;
/**
* @Acthor:
* @ClassName:
* @Description:
*/
public class MainDemo {
public static void main(String[] args){
BookShelf bookShelf =new BookShelf(4);
bookShelf.appendBook(new book("A"));
bookShelf.appendBook(new book("C"));
bookShelf.appendBook(new book("B"));
Iterator iterator = bookShelf.iterator() ;
while(iterator.hasNext()){
book b = (book) iterator.next();
System.out.print(b.getName());
}
}
}
以上就是迭代模式的一個小程序,可以看出要想使用迭代模式開發程序首先需要一個Iterator接口(迭代器),接口中定義你所需要的方法。然后定一個Aggregate接口是生成一個迭代器,該接口是實現
BookShelfIterator 書柜(容器)的遍歷。再定義一個你所需要遍歷的對象book類和需要存儲book對象的BookShref書柜(容器)。