1
2
3 import java.util.Vector;
4
5 interface Aggregate {
6 public abstract Iterator iterator();
7 }
8
9 interface Iterator {
10 public abstract boolean hasNext();
11 public abstract Object next();
12 }
13
14 class Book {
15 private String name = "";
16 public Book(String name) {
17 this.name = name;
18 }
19 public String getName() {
20 return name;
21 }
22 }
23
24 class BookShelf implements Aggregate {
25 private Vector books;
26 public BookShelf(int initialsize) {
27 this.books = new Vector(initialsize);
28 }
29 public Book getBookAt(int index) {
30 return (Book)books.get(index);
31 }
32 public void appendBook(Book book) {
33 books.add(book);
34 }
35 public int getLength() {
36 return books.size();
37 }
38 public Iterator iterator() {
39 return new BookShelfIterator(this);
40 }
41 }
42
43 class BookShelfIterator implements Iterator {
44 private BookShelf bookShelf;
45 private int index;
46 public BookShelfIterator(BookShelf bookShelf) {
47 this.bookShelf = bookShelf;
48 this.index = 0;
49 }
50 public boolean hasNext() {
51 if(index < bookShelf.getLength()) {
52 return true;
53 } else {
54 return false;
55 }
56 }
57 public Object next() {
58 Book book = bookShelf.getBookAt(index);
59 index++;
60 return book;
61 }
62 }
63
64 public class IteratorBookShelf {
65 public static void main(String[] args) {
66 BookShelf bookShelf = new BookShelf(4);
67 bookShelf.appendBook(new Book("Around the World in 80 days"));
68 bookShelf.appendBook(new Book("Bible"));
69 bookShelf.appendBook(new Book("Cinderella"));
70 bookShelf.appendBook(new Book("Daddy-Long-Legs"));
71 Iterator it = bookShelf.iterator();
72 while(it.hasNext()) {
73 Book book = (Book)it.next();
74 System.out.println(" "+book.getName());
75 }
76 }
77 }