[目的] 提供一種方法順序訪問一個聚合對象中各個元素, 而又不需暴露該對象的內部表示。
[何時使用?] 訪問一個聚合對象的內容而無需暴露它的內部表示。支持對聚合對象的多種遍歷。為遍歷不同的聚合結構提供一個統一的接口(即, 支持多態迭代)。 [如何使用?] 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()); } } } 這樣遍歷代碼保持了統一的風格,從而使使用者不必關心遍歷的對象到底是什么類型。
|