表 1-1 类和接口的一览表
| 名字 | 说明 |
|---|---|
| Aggregate | 表示集合的接口 |
| Iterator | 遍历集合的接口 |
| Book | 表示书的类 |
| BookShelf | 表示书架的类 |
| BookShelfIterator | 遍历书架的类 |
| Main | 测试程序行为的类 |
/**
* Aggregate接口
*/
public interface Aggregate{
Iterator iterator;
}
/**
* Iterator接口
*/
public interface Iterator{
boolean hasNext();
Object next();
}
/**
* Book类
*/
public class Book {
private String name;
public Book(){}
public Book(String name) {
this.name = name;
}
public String getName() {
return this.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[] agrs){
BookShelf bookShelf = new BookShelf(2);
bookShelf.appendBook(new Book("111"));
bookShelf.appendBook(new Book("222"));
Iterator iterator = bookShelf.iterator();
while(iterator.hasNext()){
Book book = (Book)iterator.next();
System.out.println(book.getName());
}
}
}
为什么要引入Ierator这种设计模式?因为引入了Iterator后可以将遍历与实现分离开来。看遍历的代码:
while(iterator.hasNext()){
Book book = (Book)iterator.next();
System.out.println(book.getName());
}
这里只使用了Iterator的hasNext方法和next方法,并没有调用BookShelf方法。也就是说,这里的while循环不依赖于BookShelf的实现。
如果编写BookShelf的开发人员决定放弃用数组来管理文本,而是用其他的容器类,那么只需要BookShelf的iterator方法能正确地返回Iterator实例,我们不需要更改在业务中的while循环迭代遍历的代码,代码都可以正常工作。

被折叠的 条评论
为什么被折叠?



