迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。
当你需要对聚集进行多种方式遍历时,可以考虑用迭代器模式;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Aggregate<String> concreteAggregate = new ConcreteAggregate<>();
concreteAggregate.add("同学1号");
concreteAggregate.add("同学2号");
concreteAggregate.add("同学3号");
concreteAggregate.add("同学4号");
Iterator iterator = concreteAggregate.createIterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("-----------------------------");
Iterator<String> iteratorDesc = new ConcreteIteratorDesc<>(concreteAggregate);
while (iteratorDesc.hasNext()){
System.out.println(iteratorDesc.next());
}
}
}
//聚集抽象类
interface Aggregate<T> {
Iterator createIterator();
void add(T t);
T getByIndex(int index);
int getCount();
}
//具体聚集类
class ConcreteAggregate<T> implements Aggregate<T>{
private List<T> list = new ArrayList<>();
@Override
public Iterator createIterator() {
return new ConcreteIterator<>(this);
}
@Override
public void add(T t){
this.list.add(t);
}
@Override
public T getByIndex(int index){
return this.list.get(index);
}
@Override
public int getCount(){
return this.list.size();
}
}
//迭代器抽象类
interface Iterator<T> {
T next();
boolean hasNext();
T currentItem();
}
//具体迭代器类(顺序)
class ConcreteIterator<T> implements Iterator<T>{
private ConcreteAggregate<T> aggregate;
private int currentIndex = 0; //当前集合的下标
public ConcreteIterator(ConcreteAggregate<T> aggregate) {
this.aggregate = aggregate;
}
@Override
public T next() {
T t = this.currentItem();
currentIndex++;
return t;
}
@Override
public boolean hasNext() {
return currentIndex < this.aggregate.getCount();
}
@Override
public T currentItem() {
return this.aggregate.getByIndex(currentIndex);
}
}
//具体迭代器类(逆序)
class ConcreteIteratorDesc<T> implements Iterator<T>{
private Aggregate<T> aggregate;
private int currentIndex = 0; //当前集合的下标
public ConcreteIteratorDesc(Aggregate<T> aggregate) {
this.aggregate = aggregate;
this.currentIndex = aggregate.getCount() - 1;
}
@Override
public T next() {
T t = this.currentItem();
currentIndex--;
return t;
}
@Override
public boolean hasNext() {
return currentIndex >= 0;
}
@Override
public T currentItem() {
return this.aggregate.getByIndex(currentIndex);
}
}
运行结果:
同学1号
同学2号
同学3号
同学4号
-----------------------------
同学4号
同学3号
同学2号
同学1号
其实JAVA/C#的foreach in就是隐式调用了迭代器模式