复制代码
1
2
3
4
5
6public interface AbstractIterator<E> { public boolean hasNext(); public 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
33import java.util.ArrayList; import java.util.List; public abstract class AbstractObjectList<E> { protected List<E> list = new ArrayList<E>(); public AbstractObjectList() { } public AbstractObjectList(List list) { this.list = list; } public void add(E e) { this.list.add(e); } public E get(int index) { return list.get(index); } public int size() { return list.size(); } public boolean isEmpty() { return list.isEmpty(); } public abstract AbstractIterator iterator(); }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import java.util.List; /** * 抽象对象列表的实现。 * * @author zhangfly * */ public class ObjectListImpl extends AbstractObjectList { public ObjectListImpl() { } public ObjectListImpl(List list) { super(list); } @Override public AbstractIterator iterator() { return new IteratorImpl(this); } }
复制代码
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/** * 迭代器的实现。 * * @author zhangfly * * @param <T> */ public class IteratorImpl<E> implements AbstractIterator { private AbstractObjectList<E> list; private int cursor = 0; public IteratorImpl(AbstractObjectList list) { this.list = list; } @Override public boolean hasNext() { if (list.isEmpty()) { return false; } if (cursor < list.size()) { return true; } return false; } @Override public E next() { E e = null; if (cursor < list.size()) { e = list.get(cursor); cursor++; } return e; } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22public class Test { public Test() { ObjectListImpl listImpl = new ObjectListImpl(); // 添加三个不同类型的元素。 listImpl.add(new String("zhang")); listImpl.add(new Exception("phil")); listImpl.add(2019); // 迭代器遍历。 AbstractIterator iterator = listImpl.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next().toString()); } } public static void main(String[] args) { new Test(); } }
输出:
复制代码
1
2
3zhang java.lang.Exception: phil 2019
最后
以上就是正直哈密瓜最近收集整理的关于Java设计模式:迭代器模式的全部内容,更多相关Java设计模式内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复