package xin.jiangqiang.iterator;
public interface Aggregate<Book> {
Iterator<Book> iterator();
}
package xin.jiangqiang.iterator;
/**
* 书的类
*/
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
package xin.jiangqiang.iterator;
/**
* 书架类
*/
public class BookShelf implements Aggregate<Book> {
private Book[] books;//使用数组存储书架中的书
private int last = 0;//实际存储的书本数
/**
* @param maxSize 书架容量
*/
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;
}
@Override
public Iterator<Book> iterator() {
return new BookShelfIterator(this);
}
}
package xin.jiangqiang.iterator;
public class BookShelfIterator implements Iterator<Book> {
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf = bookShelf;
this.index = 0;
}
@Override
public boolean hasNext() {
if (index < bookShelf.getLength()) {
return true;
} else {
return false;
}
}
@Override
public Book next() {
Book book = bookShelf.getBookAt(index);
index++;
return book;
}
}
package xin.jiangqiang.iterator;
public interface Iterator<Book> {
boolean hasNext();
Book next();
}
package xin.jiangqiang.iterator;
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<Book> iterator = bookShelf.iterator();
while (iterator.hasNext()) {
Book book = iterator.next();
System.out.println(book.getName());
}
}
}