作用:遍历整个集合
UML类图
Aggregate接口:
public interface Aggregate { public abstract Iterator iterator(); }
Iterator接口:
public interface Iterator { public abstract boolean hasNext();//是否存在下一个 public abstract Object next();//返回当前指向的对象,并指向下一个对象 }
Book类:
public class Book { private String name; //书的名称 public Book(String name)//构造函数 { this.name = name; } public String getName()//返回书的名称 { return name; } }
BoolShelf类:
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.book[last] = book; last++; } public int getLength() //返回拥有书本数 { return last; } public Iterator iterator() //实现接口,创建书架对应的Iterator { return new BookShelfIterator(this); } }
BookShelfIterator类:
public class BookShelfIterator implement Iterator //实现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接口:抽象接口的方法,让实例的迭代器类去实现它的方法
BookShelfIterator类:继承并实现bookShlef的接口,使其适用于所有的bookShelf对象
BookShelf类:继承iterator方法去获取属于自己的迭代器(BookShelfIterator)
互相关系:Iterator可以对应多种不同实例的iterator(如BookShelf的迭代器BookShelfIterator),BookShelfIterator可以供所有的BookShelf对象使用,Aggregate接口是让BookShelf获得生成BookShelfIterator的方法