迭代器模式
-
迭代器模式结构图:
-
示例代码:
// 抽象迭代器 public interface Iterator <E>{ boolean hasNext(); E next(); } // 具体迭代器 public class ConcreteIterator<E> implements Iterator<E>{ private List<E> list; private int index = 0; public ConcreteIterator(List<E> list) { this.list = list; } @Override public boolean hasNext() { return index<list.size(); } @Override public E next() { return list.get(index++); } } // 抽象容器 public interface Aggregate<E> { boolean add(E element); boolean remove(E element); Iterator<E> iterator(); } // 具体容器 public class ConcreteAggregate<E> implements Aggregate<E>{ private List<E> list = new ArrayList<>(); @Override public boolean add(E element) { return list.add(element); } @Override public boolean remove(E element) { return list.remove(element); } @Override public Iterator<E> iterator() { return new ConcreteIterator<>(list); } } // 测试类 public class IteratorTest { public static void main(String[] args) { ConcreteAggregate<String> aggregate = new ConcreteAggregate<>(); aggregate.add("A"); aggregate.add("B"); aggregate.add("C"); aggregate.add("D"); Iterator<String> iterator = aggregate.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } } }
-
总结:
优点:简化集合对象接口,功能多样化,解偶迭代与集合;
缺点:使用迭代器遍历较为繁琐,无需自己实现,使用现有API即可.