类图:
代码示例:
package iterator;public interface Aggregate { public Iterator iterator();}
package iterator;public interface Iterator { public boolean hasNext(); public Object next();}
package iterator;public abstract class BookShelfs { public abstract void appendBook(Book book); public abstract Book getBookAt(int index); public abstract int getLength(); }
package iterator;/** * 具体的聚合器 */public class BookShelf extends BookShelfs implements Aggregate { private Book[] books; //标记目前书架上有多少书 private int last; public BookShelf(int maxsize){ books = new Book[maxsize]; last = 0; } @Override public Book getBookAt(int index){ return books[index]; } @Override public void appendBook(Book book){ /*实际上应该有一个最大容量的判断,如果超出了数组边界,会抛出越界异常 (就看这里是由编程者自己做处理还是让编译器抛异常,上层程序再来处理) 如果是类的开发者,应该是会选择让上层程序来处理 */ books[last]=book; last++; } @Override public int getLength(){ return last; } @Override public Iterator iterator() { //直接创建使用一个迭代器 return new BookShelfIterator(this); }}
package iterator;import java.util.Vector;public class BookShelf2 extends BookShelfs implements Aggregate { private Vectorbooks; public BookShelf2(){ books = new Vector (); } @Override public void appendBook(Book book){ books.add(book); } @Override public Book getBookAt(int index){ return books.get(index); } @Override public int getLength() { return books.size(); } @Override public Iterator iterator() { return new BookShelfIterator(this); }}
package iterator;public class BookShelfIterator implements Iterator { private BookShelfs bookShelf; //记录下当前迭代的位置 private int index; public BookShelfIterator(BookShelfs bookShelf){ this.bookShelf = bookShelf; index = 0; } @Override public boolean hasNext() { if(index
package iterator;public class Book { private String name; public Book(){} public Book(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
package iterator;public class Client { public static void main(String[] args) { //数组存储书籍 BookShelf myShelf = new BookShelf(10); //以一种不同的组织方式组织书的书架(Vector存放书籍) BookShelf2 otherShelf = new BookShelf2(); myShelf.appendBook(new Book("thinking in java")); myShelf.appendBook(new Book("effective java")); myShelf.appendBook(new Book("design patterns")); otherShelf.appendBook(new Book("head first java")); otherShelf.appendBook(new Book("head first design pattern")); Iterator it = new BookShelfIterator(myShelf); while(it.hasNext()){ Book b = (Book) it.next(); System.out.println(b.getName()); } it = new BookShelfIterator(otherShelf); while(it.hasNext()){ Book b = (Book) it.next(); System.out.println(b.getName()); } }}
运行结果:
thinking in javaeffective javadesign patternshead first javahead first design pattern