设计模式——迭代器模式

什么是迭代器模式

当我们进行数组遍历的时候需要for循环i一直到arr.length,当我们使用迭代器模式的时候我们只需要生成当前数组的具体迭代器(实现迭代器接口),然后通过这个迭代器遍历就行。

迭代器UML图及角色介绍

迭代器模式

Aggregate接口

Aggregate是所有需要通过迭代器遍历的集合的接口。所有需要通过迭代器遍历集合的都需要实现这个Aggregate接口,Aggregate本身有聚集集合的意思,这里我们就叫它有迭代器实现的集合接口吧。

其中相关Aggregate接口的代码如下:

1
2
3
4
public interface Aggregate {
//这里实现了一个迭代器,需要实现迭代器的集合都必须实现这个方法,这个方法的目的是返回该集合的具体迭代器。
Interator iterator();
}

ConcreteAggregate实现类

ConcreteAggregate实现了Aggregate接口,可以说是具体的实现类,比如说这个类是一个CardList(里面存放了card元素),里面会有相关的card字段以及获取某个元素,获取长度等等有关集合数组的操作。最重要的是它需要实现iterator方法。

其中相关ConcreteAggregate实现类的代码如下:

1
2
3
public Iterator iteratot(){
return new ConcreteIterator(this);
}

Iterator接口

Iterator和Aggregate接口的关系就是,Aggregate接口中有产生Iterator的iterator方法,也就是Aggregate接口的具体实现类ConcreteAggregate产生出Iterator具体实现类ConcreteIterator。

其中Iterator中有两个方法,分别是hasNext(),next()。hasNext的作用是判断迭代器是否还有下一个元素,如果有返回true否则false。next()的作用是返回当前集合迭代到的元素并将指针移向一下个元素(注意这里是两个作用)。

所以有了迭代器我们遍历一个集合是这样的

1
2
3
4
5
6
7
//用于产生cardList的迭代器
//这个方法这里还是不可以用的,为了现在介绍迭代器迭代代码,如果要实现必须要有一个具体ConcreteIterator实现类
Iteratot iterator = cardList.iterator();
while(it.hasNext()){
Card card = (Card)iterator.next();
//.......进行相关操作
}

具体Iterator接口的实现代码如下:

1
2
3
4
public interface Iterator{
boolean hasNext();
Object next();
}

ConcreteIterator实现类

ConcreteIterator实现了Iterator接口,比如我们这里实现的是CardList的Iterator,我们可以这样写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class CardListIterator implements Iterator{
private CardList cardList;
private int index;
public CardListIterator(CardList catdList){
this.cardList = cardList;
this.index = 0;
}
public boolean hasNext(){
return index < cardList.getLength();
}
public Object next(){
Card card = CardList.get(index);
index ++ ;
return card;
}
}

迭代器模式的作用

为什么要考虑引入Iterator模式呢?直接for循环不就好了,其实迭代器模式有一个好处就是分离,将遍历和实现分开来,在我们调用如下代码的时候

1
2
3
4
while(it.hasNext()){
Card card = (Card)iterator.next();
//.......进行相关操作
}

这个遍历并没有依赖于cardList,所以当我们这个cardList切换了数据结构的时候我们不需要将原来代码的for循环再依次改动了,我们只需要修改这个相关的iterator的具体实现类其中的hasNext()方法和next()方法就行了。

-------------本文结束感谢阅读-------------