[目的] 提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
[何时使用?] 访问一个聚合对象的内容而无需暴露它的内部表示。支持对聚合对象的多种遍历。为遍历不同的聚合结构提供一个统一的接口(即, 支持多态迭代)。 [如何使用?] Java风格的示例程序: //抽象的集合 public interface Aggregate { public abstract Iterator iterator(); } //抽象的Iterator public interface Iterator { public abstract boolean hasNext(); public abstract Object next(); } //具体的集合 public class ConcreteAggregate implements Aggregate { private Object[] collection; private int last = 0; public ConcreteAggregate() { collection = new Object[3]; } public Object getItemAt(int index) { return collection[index]; } public void appendItem(Object item) { this.collection[last] = item; last++; } public int getLength() { return last; } public Iterator iterator() { //产生适合自己的Iterator return new ConcreteIterator(this); } } //具体的Iterator public class ConcreteIterator implements Iterator { private ConcreteAggregate namecollection; //由它决定遍历的集合类型 private int index; public ConcreteIterator(ConcreteAggregate collection) { this.namecollection = collection; this.index = 0; } public boolean hasNext() { if (index < namecollection.getLength()) { return true; } else { return false; } } public Object next() { //通过统一的getItemAt()接口实现对不同类型集合的遍历 Object item = namecollection.getItemAt(index); index++; return item; } } public class IteratorExample { public static void main(String[] args) { ConcreteAggregate collection = new ConcreteAggregate(); collection.appendItem(new Person("Davis")); collection.appendItem(new Person("Frank")); collection.appendItem(new Person("Jeny")); //it的具体类型依赖于collection的类型而使用者并不需要关心这里面的区别 Iterator it = collection.iterator(); //返回适合collection的iterator while (it.hasNext()) { Person person = (Person)it.next(); System.out.println("" + person.getName()); } } } 这样遍历代码保持了统一的风格,从而使使用者不必关心遍历的对象到底是什么类型。
|