[size=medium] [b]Iterator迭代子模式定义[/b][/size]
一般是对集合进行遍历使用,java的集合类都可以迭代,一般不需要自己设计Iterator
当然也可以自己设计迭代器,比如一个书架类,里面有个书本的数组属性,可以自己设计一个迭代器,对书架里面的书本进行迭代:
[img]http://dl.iteye.com/upload/attachment/0072/4118/d8193e71-b7a9-365c-96fc-4dad636a2b66.jpg[/img]
一般是对集合进行遍历使用,java的集合类都可以迭代,一般不需要自己设计Iterator
package iterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
//获取List的迭代器
Iterator<String> it = list.iterator();
//迭代遍历List中的元素
while(it.hasNext())
System.out.println(it.next());
}
}
当然也可以自己设计迭代器,比如一个书架类,里面有个书本的数组属性,可以自己设计一个迭代器,对书架里面的书本进行迭代:
package com.pattern.iterator;
public class BookShelfIterator implements 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;
}
}
package com.pattern.iterator;
/**
* 书架类
* @author administrator
*/
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 books.length;
}
//获得书架迭代器对象
public Iterator iterator() {
return new BookShelfIterator(this);
}
[img]http://dl.iteye.com/upload/attachment/0072/4118/d8193e71-b7a9-365c-96fc-4dad636a2b66.jpg[/img]