public class ConcreteAggregate implements Aggregate { private List list = new ArrayList<>(); @Override public void add(E data) { list.add(data); } @Override public void remove(E data) { list.remove(data); } @Override public Iterator iterator() { return new InnerIterator(); } /** * 迭代器 */ private class InnerIterator implements Iterator { private int cursor; @Override public boolean hasNext() { return cursor } @Override public E next() { E data = list.get(cursor); cursor++; return data; } } }
测试,使用起来和 Java 内置的集合是不是很像。
public static void main(String args[]) { Aggregate aggregate = new ConcreteAggregate<>(); aggregate.add("小刘"); aggregate.add("小李"); aggregate.add("小王"); Iterator iterator = aggregate.iterator(); while (iterator.hasNext()) { String name = iterator.next(); System.out.println(name); } }