/*
* 需要遍历的集合的接口,实现该接口的类将成为一个可以保存多个元素的集合
* */
public interface Aggregate {
//遍历集合的迭代器
public abstract Iterator iteraor();
}
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) {
books[last] = book;
last++;
}
public int getBookCount() {
return last;
}
@Override
public Iterator iteraor() {
return new BookShelfIterator(this);
}
}
public interface Iterator {
//判断是否还有下一个元素
public abstract boolean hasNext();
//返回当前元素,且指针指向下一个元素
public abstract Object next();
}
public class BookShelfIterator implements Iterator {
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf = bookShelf;
this.index = 0;
}
@Override
public boolean hasNext() {
if(index < bookShelf.getBookCount()) {
return true;
}
return false;
}
@Override
public Object next() {
Book book = bookShelf.getBookAt(index);
index++;
return book;
}
}
/*
* 书的实体类
* */
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
'}';
}
}
UML图