迭代器(Iterator)模式,又叫做游標(Cursor)模式。GOF給出的定義為:提供一種方法訪問一個容器(container)對象中各個元素,而又不需暴露該對象的內部細節。
迭代器模式由以下角色組成:
迭代器角色(Iterator):迭代器角色負責定義訪問和遍歷元素的接口。
具體迭代器角色(Concrete Iterator):具體迭代器角色要實現迭代器接口,并要記錄遍歷中的當前位置。
容器角色(Container):容器角色負責提供創建具體迭代器角色的接口。
具體容器角色(Concrete Container):具體容器角色實現創建具體迭代器角色的接口。這個具體迭代器角色與該容器的結構相關。
Java實現示例
類圖:
代碼:
1
2
3
4
5
6
7
8
9
10
11
12
|
/** * 自定義集合接口, 類似java.util.Collection * 用于數據存儲 * @author stone * */ public interface ICollection<T> { IIterator<T> iterator(); //返回迭代器 void add(T t); T get( int index); } |
1
2
3
4
5
6
7
8
9
10
11
12
|
/** * 自定義迭代器接口 類似于java.util.Iterator * 用于遍歷集合類ICollection的數據 * @author stone * */ public interface IIterator<T> { boolean hasNext(); boolean hasPrevious(); T next(); T previous(); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
/** * 集合類, 依賴于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]; } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
/* * 若有新的存儲結構,可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); } } } |
打印:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
3 5 8 12 3 3 5 ------------- a b c 3 8 12 3 5 |