Iterator ——迭代器
程序示例
Aggregate 接口
public interface Aggregate {
public Iterator Iterator();
}
Iterator 接口
public interface Iterator {
public boolean hasNext();
public Object next();
}
Book 类
public class Book {
private String name = "";
public Book(String name) {
this.name = name;
}
public String getName() {
return 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[] 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 iterator = bookShelf.iterator();
while (iterator.hasNext()) {
Book book = (Book)iterator.next();
System.out.println("" + book.getName());
}
}
}
Iterator Pattern 的所有参与者
- Iterator(迭代器) 参与者
- ConcreteIterator(具体迭代器) 参与者
- Aggregate(聚合) 参与者
- ConcreteAggregate(具体聚合) 参与者
扩展自我视野的提示
无论实现结果如何,都能使用Iterator
设计Pattern的目的就是为了提高类的复用率。提高复用率则是指吧类当作一个零件来使用,只要修改某一个零件,就不需要大费周章去修改其他的零件。
抽象类、接口实在很难搞
过度依赖具体类反而会提高类与类的耦合度,增加零部件复用的困难。为了降低耦合度,让类作为零部件再利用,必须引进抽象类和接口的概念。
“下一个”容易搞错
返回现在的元素,同时进行到下一个位置。
练习题
问题1
若书籍数量超过最先设定的书架大小,就无法继续把书放上去。请利用java.util.Vector取代数组,把程序改成即使已经超过书架容量也能继续新增书籍。
答案
import java.util.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.length;
}
public Iterator iterator() {
return new BookShelfIterator(this);
}
}