迭代器模式

一种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。

Class Diagram

Implementation

迭代器接口

1
2
3
4
5
6
7
8
9
10
11
12
13
public interface Iterator<E> {
/**
* 是否有下一个元素
* @return 是|否
*/
boolean hasNext();

/**
* 获取下一个元素
* @return 元素
*/
E next();
}

迭代器实现类

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
/**
* Created with IntelliJ IDEA.
* User: 长歌
* Date: 2019/11/15
* Description: 词典
*/
public class Dictionary {

private String words[] = {"hello","world","leithda"};


public Iterator<String> iterator(){
return new Itr();
}

private class Itr implements Iterator<String> {
int cursor;
int lastRet = -1;

@Override
public boolean hasNext() {
return cursor != words.length;
}

@Override
public String next() {
int i = cursor;
if(i >= words.length){

}
cursor = i+1;
return words[lastRet = i];
}
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class IteratorTest {

@Test
public void test() throws Exception{
Dictionary dictionary = new Dictionary();

Iterator it = dictionary.iterator();

while(it.hasNext()){
System.out.println(it.next());
}
}

}

Example

Refence