Java代码实现:
package com.freedie.iteratorpattern;
/**
* 书籍实体类
* @author threedie.qin
* @date2011-10-30 @ti下午05:18:02
*/
public class Book {
private String name;
public Book(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
package com.freedie.iteratorpattern;
/**
* 迭代器接口,真正进行迭代功能的接口
* @author threedie.qin
* @date2011-10-30 @ti下午05:10:04
*/
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
package com.freedie.iteratorpattern;
/**
* 标示可以迭代的接口,如果某一个类需要实现迭代的功能,实现该接口即可
* @author threedie.qin
* @date2011-10-30 @ti下午05:09:05
*/
public interface Iteratorable {
public abstract Iterator iterator();
}
package com.freedie.iteratorpattern;
/**
* 书柜实体类
* @author threedie.qin
* @date2011-10-30 @ti下午05:18:12
*/
public class BookShelf implements Iteratorable {
private Book[] bookArray;
private int index = 0;
public BookShelf(int arrayLength){
bookArray = new Book[arrayLength];
}
/**
* 往书柜上添加书籍
* @param book
* @return
*/
public BookShelf appendBook(Book book){
bookArray[index ++] = book;
return this;
}
/**
* 根据索引得到书柜上的书籍
* @param index
* @return
*/
public Book getBookAtPosition(int index){
return bookArray[index];
}
/**
* 得到书柜上的书籍的总数
* @return
*/
public int getLength(){
return this.bookArray.length;
}
/**
* 得到书柜的迭代器对象
*/
@Override
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
package com.freedie.iteratorpattern;
/**
* 书柜迭代器对象
* @author threedie.qin
* @date2011-10-30 @ti下午05:19:27
*/
public class BookShelfIterator implements Iterator{
private BookShelf bookShelf;
private int currentIndex;
public BookShelfIterator(BookShelf bookShelf){
this.bookShelf = bookShelf;
this.currentIndex = 0;
}
/**
* 判断是否还有下一个元素
*/
@Override
public boolean hasNext() {
return this.currentIndex < bookShelf.getLength() ? true : false;
}
/**
* 返回下一个元素
*/
@Override
public Object next() {
return bookShelf.getBookAtPosition(currentIndex ++);
}
}
package com.freedie.iteratorpattern;
/**
* 迭代器模式测试类
* @author threedie.qin
* @date2011-10-30 @ti下午05:15:32
*/
public class TestIteratorPattern {
public static void main(String[] args) {
BookShelf bookShelf = new BookShelf(5);
bookShelf.appendBook(new Book("Android Programming")).
appendBook(new Book("Linux kenerl design and programming")).
appendBook(new Book("Java multithread programming")).
appendBook(new Book("Java net programming")).
appendBook(new Book("html5 programming"));
Iterator it = bookShelf.iterator();
while(it.hasNext()){
Object object = it.next();
if(object instanceof Book){
Book book = (Book)object;
System.out.println(book.getName());
}
}
}
}