设计模式学习与整理-迭代器模式
介绍
迭代器模式(Iterator Pattern)用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。 迭代器模式属于行为型模式。
应用场景
(1)让用户访问一个集合中对象,但不想暴露对象在集合中的存储结构。
(2)希望对遍历不同的集合提供一个统一的接口。
模式结构
(1)集合(Aggregate):一个接口,规定了具体集合需实现的操作。
(2)具体集合(ConcreteAggregate):具体集合是实现集合接口的类的实例,具体集合按照一定的结构存储对象。具体集合应当有一个方法,该方法返回一个针对该集合的具体迭代器。
(3)迭代器(Iterator):一个接口,规定了遍历集合的方法,比如next()方法。
(4)具体迭代器(ConcreteIterator):实现迭代器接口的类的实例,具体迭代器在实现迭代器接口所规定的遍历集合的方法时,比如next()方法,要保证next()方法的首次调用即按照集合的数据结构找到该集合中的一个对象,而且每当找到集合中的一个对象,立刻根据该集合的存储结构得到待遍历的后继对象的引用,并保证依次调用next()方法可以遍历集合。
代码案例
首先创建迭代器接口,接口中有hasNext()和next():
public interface Iterator<E> {
boolean hasNext();
E next();
}
创建集合接口:
public interface Aggregate<E> {
Iterator<E> getIterator();
void add(E obj);
E get(int index);
int getSize();
}
迭代器接口的实现类:
public class ConcreteIterator implements Iterator {
private Aggregate aggregate;
private int index;
ConcreteIterator(Aggregate aggregate) {
this.aggregate = aggregate;
}
@Override
public boolean hasNext() {
return index < aggregate.getSize();
}
@Override
public Object next() {
return aggregate.get(index++);
}
}
创建集合的实现类,实现一些操作集合中数据的方法:
public class ConcreteAggregate implements Aggregate {
private Object[] list;
private int size = 0;
private int index = 0;
public ConcreteAggregate(){
index = 0;
size = 0;
list = new Object[100];
}
@Override
public Iterator getIterator() {
return new ConcreteIterator(this);
}
@Override
public void add(Object obj) {
list[index++] = obj;
size++;
}
@Override
public Object get(int index) {
return list[index];
}
@Override
public int getSize() {
return size;
}
}
测试类:
public class ApplicationTest {
public static void main(String[] args) {
ConcreteAggregate concreteAggregate = new ConcreteAggregate();
concreteAggregate.add(1);
concreteAggregate.add(2);
concreteAggregate.add(3);
concreteAggregate.add(4);
concreteAggregate.add(5);
Iterator iterator = concreteAggregate.getIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
优点
(1)增加新的聚合类和迭代器类都很方便,无须修改原有代码。
(2)用户使用迭代器模式访问集合中的对象,而不需要知道这些对象在集合中是如何表达及存储的。
缺点
由于迭代器模式将存储数据和遍历数据的职责分离,增加新的聚合类需要对应增加新的迭代器类,类的个数成对增加,这在一定程度上增加了系统的复杂性。