迭代器模式

迭代器模式可以让你对聚集有多种遍历方式.
它分离了集合对象的遍历行为,抽象出一个迭代器来负责,这样既可以做到不暴露集合的内部结构,又可让外部代码透明的访问集合内部的数据.

1
2
3
4
5
6
7
8
9
10
package iterator;

/**
* Created by hero on 17-2-20.
*/
public interface Iterator<E> {
boolean hasNext();
E next();
}

1
2
3
4
5
6
7
8
9
package iterator;

/**
* Created by hero on 17-2-20.
*/
public interface Aggregate<E> {
Iterator<E> createIterator();
}

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
47
48
49
50
package iterator;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
* Created by hero on 17-2-20.
*/
public class ConcreteAggregate<T> implements Aggregate<T> {
private List<T> list;
private int count;
private int current;

public void push(T e) {
list.add(e);
count++;
}

public void remove(T e) {
list.remove(e);
count--;
}

public ConcreteAggregate() {
list = new ArrayList<>();
count = 0;
current = 0;
}

@Override
public Iterator<T> createIterator() {
return new Iter<T>();
}

/** 内部类 */
private class Iter<T> implements Iterator<T> {

@Override
public boolean hasNext() {
return current < count;
}

@Override
public T next() {
return (T) list.get(current++);
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package iterator;

/**
* Created by hero on 17-2-20.
*/
public class Main {
public static void main(String[] args) {
ConcreteAggregate<Integer> aggregate = new ConcreteAggregate<>();
aggregate.push(1);
aggregate.push(2);

Iterator iter = aggregate.createIterator();

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