标签:
提供一种方法顺序访问一个聚合对象中的各个元素,而不暴露该对象的内部表示
package com.hml.iterator; public interface Iterator { public Object first(); public Object next(); public boolean hasNext(); public Object curItem(); public void add(Object o); }
package com.hml.iterator; import java.util.ArrayList; import java.util.List; public class Aggregate implements Iterator { private List<Object> items = new ArrayList<Object>(); private int count = 0; public Object first() { return items.get(0); } public Object next() { return items.get(++count); } public boolean hasNext() { return count < items.size(); } public Object curItem() { return items.get(count); } public void add(Object o) { items.add(o); } }
package com.hml.iterator; public class Test { public static void main(String[] args) { Aggregate a = new Aggregate(); a.add(1); a.add(2); a.add(3); System.out.println(a.curItem()); System.out.println(a.next()); System.out.println(a.first()); System.out.println(a.hasNext()); } }
当需要对聚合对象进行遍历时,可以考虑使用迭代器模式。
标签:
原文地址:http://www.cnblogs.com/heml/p/4649653.html