迭代器模式

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
37
38
39
40
41
42
43
44
45
46
interface Iterator {
boolean hasNext();

Object next();
}

interface Container {
Iterator getIterator();
}

class NameRepository implements Container {
public String[] names = {"Robert", "John", "Julie", "Lora"};

@Override
public Iterator getIterator() {
return new NameIterator();
}

private class NameIterator implements Iterator {

int index;

@Override
public boolean hasNext() {
return index < names.length;
}

@Override
public Object next() {
if (this.hasNext()) {
return names[index++];
}
return null;
}
}
}

public class IteratorPatternDemo {
public static void main(String[] args) {
NameRepository namesRepository = new NameRepository();
for (Iterator iter = namesRepository.getIterator(); iter.hasNext(); ) {
String name = (String) iter.next();
System.out.println("Name : " + name);
}
}
}

迭代器模式
https://wangqian0306.github.io/2021/design-iterator-pattern/
作者
WangQian
发布于
2021年7月22日
许可协议