迭代器(Iterator)模式,又叫做游標(Cursor)模式。GOF給出的定義為:提供一種方法訪問一個容器(container)對象中各個元素,而又不需暴露該對象的內部細節。
迭代器模式由以下角色組成:
迭代器角色(Iterator):迭代器角色負責定義訪問和遍歷元素的接口。
具體迭代器角色(Concrete Iterator):具體迭代器角色要實現迭代器接口,并要記錄遍歷中的當前位置。
容器角色(Container):容器角色負責提供創建具體迭代器角色的接口。
具體容器角色(Concrete Container):具體容器角色實現創建具體迭代器角色的接口。這個具體迭代器角色與該容器的結構相關。
Java實現示例
類圖:

代碼:
/** * 自定義集合接口, 類似java.util.Collection * 用于數據存儲 * @author stone * */ public interface ICollection<T> { IIterator<T> iterator(); //返回迭代器 void add(T t); T get(int index); } /** * 自定義迭代器接口 類似于java.util.Iterator * 用于遍歷集合類ICollection的數據 * @author stone * */ public interface IIterator<T> { boolean hasNext(); boolean hasPrevious(); T next(); T previous(); } /** * 集合類, 依賴于MyIterator * @author stone */ public class MyCollection<T> implements ICollection<T> { private T[] arys; private int index = -1; private int capacity = 5; public MyCollection() { this.arys = (T[]) new Object[capacity]; } @Override public IIterator<T> iterator() { return new MyIterator<T>(this); } @Override public void add(T t) { index++; if (index == capacity) { capacity *= 2; this.arys = Arrays.copyOf(arys, capacity); } this.arys[index] = t; } @Override public T get(int index) { return this.arys[index]; } } /* * 若有新的存儲結構,可new 一個ICollection, 對應的 new 一個IIterator來實現它的遍歷 */ @SuppressWarnings({"rawtypes", "unchecked"}) public class Test { public static void main(String[] args) { ICollection<Integer> collection = new MyCollection<Integer>(); add(collection, 3, 5, 8, 12, 3, 3, 5); for (IIterator<Integer> iterator = collection.iterator(); iterator.hasNext();) { System.out.println(iterator.next()); } System.out.println("-------------"); ICollection collection2 = new MyCollection(); add(collection2, "a", "b", "c", 3, 8, 12, 3, 5); for (IIterator iterator = collection2.iterator(); iterator.hasNext();) { System.out.println(iterator.next()); } } static <T> void add(ICollection<T> c, T ...a) { for (T i : a) { c.add(i); } } } 打印:
3 5 8 12 3 3 5 ------------- a b c 3 8 12 3 5
新聞熱點
疑難解答