// 建立一个可对应聚合的iteratorpublic interface Aggregate { public Iterator Iterator();}
Iterator 接口
public interface Iterator { public boolean hasNext(); public Object next();}
Book 类
public class Book { PRivate String name = ""; public Book(String name) { this.name = name; } public String getName() { return name; }}
BookShelf 类
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 last; } public Iterator iterator() { return new BookShelfIterator(this); }}
BookShelfIterator 类
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; }}
Main 类
public class Main { public static void main(String[] args) { BookShelf bookShelf = new BookShelf(4); bookShelf.appendBook(new Book("Around the World in 80 Days")); bookShelf.appendBook(new Book("Bible")); bookShelf.appendBook(new Book("Cinderella")); bookShelf.appendBook(new Book("Daddy-Long-Legs")); Iterator iterator = bookShelf.iterator(); while (iterator.hasNext()) { Book book = (Book)iterator.next(); System.out.println("" + book.getName()); } }}
import java.util.Vector;public class BookShelf implements Aggregate { private Vector books; public BookShelf(int initialsize) { this.books = new Vector(initialsize); } public Book getBookAt(int index) { return (Book)books.get(index); } public void appendBook(Book book) { books.add(book); } public int getLength() { return books.length; } public Iterator iterator() { return new BookShelfIterator(this); }}