http://drive.google.com/uc?export=view&id=0ByLqiEM75qEzamh3SXpSejdwZk0
반복자 패턴 클래스 다이어그램
Iterator it = bookShelf.iterator();
while (it.hasNext()) {
Book book = (Book)it.next();
System.out.println("" + book.getName());
}
BookShelf books 배열 사용
public interface Aggregate {
public abstract Iterator iterator();
}
public class Book {
private String name = "";
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
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);
}
public Book[] getBooks() {
return books;
}
public void setBooks(Book[] books) {
this.books = books;
}
}
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;
}
}
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
BookShelf books 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.size();
}
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
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"));
bookShelf.appendBook(new Book("East of Eden"));
bookShelf.appendBook(new Book("Frankenstein"));
bookShelf.appendBook(new Book("Gulliver's Travels"));
bookShelf.appendBook(new Book("Hamlet"));
Iterator it = bookShelf.iterator();
while (it.hasNext()) {
Book book = (Book)it.next();
System.out.println("" + book.getName());
}
}
}