定义
迭代器模式(lterator Pattern)又称为游标模式(Cursor Pattern),它提供一种顺序访问集合或容器对象元素的方法,而又无须暴露集合内部表示。迭代器模式可以为不同的容器提供一致的遍历行为,而不用关心容器内容元素组成结构,属于行为型模式。
适用场景
我们把多个对象聚在一起形成的总体称之为集合,集合对象是能够包容一组对象的容器对象。不同的集合其内部元素的聚合结构可能不同,而迭代器模式屏蔽了内部元素获取细节,为外部提供一致的元素访问行为,解耦了元素迭代与集合对象间的耦合,并且通过提供不同的迭代器,可以为同个集合对象提供不同顺序的元素访问行为,扩展了集合对象元素迭代功能,符合开闭原则。迭代器模式适用于以下场景:
1、访问一个集合对象的内容而无需暴露它的内部表示;
2、为遍历不同的集合结构提供一个统一的访问接口。
代码实现
//抽象迭代器
public interface Iterator<E> {
E next();
boolean hasNext();
}
//抽象容器
public interface IAggregate<E> {
boolean add(E element);
boolean remove(E element);
Iterator<E> iterator();
}
//具体迭代器
public class ConcreteIterator<E> implements Iterator<E> {
private List<E> list;
private int cursor = 0;
public ConcreteIterator(List<E> list) {
this.list = list;
}
public E next() {
return this.list.get(this.cursor ++);
}
public boolean hasNext() {
return this.cursor < this.list.size();
}
}
//具体容器
public class ConcreteAggregate<E> implements IAggregate<E> {
private List<E> list = new ArrayList<E>();
public boolean add(E element) {
return this.list.add(element);
}
public boolean remove(E element) {
return this.list.remove(element);
}
public Iterator<E> iterator() {
return new ConcreteIterator<E>(this.list);
}
}
public class Test {
public static void main(String[] args) {
//来一个容器对象
IAggregate<String> aggregate = new ConcreteAggregate<String>();
//添加元素
aggregate.add("one");
aggregate.add("two");
aggregate.add("three");
//获取容器对象迭代器
Iterator<String> iterator = aggregate.iterator();
//遍历
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
}
}
优缺点
优点:
1、多态迭代:为不同的聚合结构提供一致的遍历接口,即一个迭代接口可以访问不同的集合对象;
2、简化集合对象接口:迭代器模式将集合对象本身应该提供的元素迭代接口抽取到了迭代器中,使集合对象无须关心具体迭代行为;
3、元素迭代功能多样化:每个集合对象都可以提供一个或多个不同的迭代器,使的同种元素聚合结构可以有不同的迭代行为;
4、解耦迭代与集合:迭代器模式封装了具体的迭代算法,迭代算法的变化,不会影响到集合对象的架构。
缺点:
对于比较简单的遍历(像数组或者有序列表),使用迭代器方式遍历较为繁琐。