Iterator Pattern 是指依序遍历并处理多个数字或变量.iterator为迭代器.
Aggregate接口
是一个执行递增的"聚合".实现此接口的类就变成类似数组的"多个数字或者变量等的聚合".
Aggregate 表示已聚合的接口
Iterator 执行递增,遍历的接口
Book 表示书籍的类
BookShelf 表示书架的类
BookShelfIterator 扫描书架的类
Main 测试用类
为什么要使用Iterator模式,为什么不用for循环进行处理?
因为利用Iterator可以跟实现分开,单独进行递增.
在迭代的过程总,只用到了hasNext()和next()方法,而跟BookShelf无关,如果以后把BookShelf利用java.util.Vector实现,也不会影响程序运行。
package com.sw.IteratorPattern;
/**
* 迭代器参与者
* 定义访问和遍历元素的接口。
* @author sw
*
*/
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
package com.sw.IteratorPattern;
/**
* 实现Iterator接口即可将BookShelfIterator视为Iterator进行处理。
* BookShelf字段为BookShelfIterator所扫描的书架,而index字段则是指向目前该书的下标
* 具体迭代器,实际上实现Iterator所定义的接口。
* @author sw
*
*/
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.sw.IteratorPattern;
/**
* Aggregate(聚合)参与者
* 定义建立Iterator参与者的接口。
* @author sw
*
*/
public interface Aggregate {
public abstract Iterator iterator();
}
package com.sw.IteratorPattern;
/**
* BookShelf类
* 实现了Aggregate接口。
* 实现其迭代器操作。
* ConcreteAggregate(具体聚合)参与者
* @author sw
*
*/
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){
if(this.last >= this.books.length){
System.out.println("该书架不能容纳超过["+this.books.length+"]本书!");
System.out.println("需要加入的名字为["+book.getName()+"]的书未加入书架!");
}else{
this.books[last++] = book ;
}
}
public int getLength(){
return last ;
}
public Iterator iterator(){
return new BookShelfIterator(this);
}
}
package com.sw.IteratorPattern;
/**
* Book类
* @author sw
*
*/
public class Book {
private String name ="";
public Book(String name){
this.name = name ;
}
public String getName(){
return name ;
}
}
package com.sw.IteratorPattern;
/**
* 测试程序
* @author sw
*
*/
public class main {
public static void main(String[] args){
BookShelf bs = new BookShelf(4);
bs.appendBook(new Book("哈里波特"));
bs.appendBook(new Book("指环王"));
bs.appendBook(new Book("蜘蛛侠1"));
bs.appendBook(new Book("蜘蛛侠2"));
bs.appendBook(new Book("蜘蛛侠3"));
System.out.println("输出书架所有的书籍:");
Iterator it = bs.iterator();
while(it.hasNext()){
Book bk = (Book)it.next();
System.out.println(""+bk.getName());
}
}
}