迭代器模式
迭代器模式提供了遍历容器的方便性,容器只要管理增减元素即可,需要遍历的时候交由迭代器进行。
比如Set、Map、List等容器的iterator。
定义
迭代器是为容器服务的,它提供一种方法访问一个容器对象中的各个元素,而又不需要暴露该对象的内部细节。

实现
Iterator
抽象迭代器负责定义访问和遍历元素的接口。
first() 获取第一个元素;
next() 访问下一个元素;
hasNext() 是否还有下一个;
1 2 3 4 5
| public interface Iterator<E>{ E next(); boolean hasNext(); boolean remove(); }
|
ConcreteIterator
具体迭代器要实现迭代器接口,完成容器元素的遍历。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class ConcreteIterator implements Iterator<E>{ private Vector<E> v = new Vector<>(); public int cursor = 0; public ConcreteIterator(Vector _vector){ this.v = _vector; } public boolean hasNext(){ return this.cursor != this.v.size(); }
public E next(){ return this.hasNext() ? this.v.get(this.cursor++) : null; }
public boolean remove(){ this.v.remove(this.cursor); return true; } }
|
Aggregate
抽象容器角色负责提供创建具体迭代器角色的接口, 必然提供一个类似于createIterator()的方法。
1 2 3 4 5
| public interface Aggregate<E>{ void add(E e); void remove(E e); Iterator iterator(); }
|
Concrete Aggregate
具体容器实现容器接口定义的方法,创建出容纳迭代器的对象。
1 2 3 4 5 6 7 8 9 10 11 12
| public class ConcreteAggrate implements Aggregate<E>{ Vector v = new Vector(); public void add(E e){ this.add(e); } public Iterator<E> iterator(){ return new ConcreteIterator<>(this.v); } public void remove(E e){ this.remove(e); } }
|