经典的设计模式有23种,但是常用的设计模式一般情况下不会到一半,我们就针对一些常用的设计模式进行一些详细的讲解和分析,方便大家更加容易理解和使用设计模式。
1-原理和实现
迭代器模式(Iterator Design Pattern),也叫作游标模式(Cursor Design Pattern)。它用来遍历集合对象。这里说的“集合对象”也可以叫“容器”“聚合对象”,实际上就是包含一组对象的对象,比如数组、链表、树、图、跳表。迭代器模式将集合对象的遍历操作从集合类中拆分出来,放到迭代器类中,让两者的职责更加单一。
迭代器是用来遍历容器的,所以,一个完整的迭代器模式一般会涉及容器和容器迭代器两部分内容。为了达到基于接口而非实现编程的目的,容器又包含容器接口、容器实现类,迭代器又包含迭代器接口、迭代器实现类。容器中需要定义iterator()方法,用来创建迭代器。迭代器接口中需要定义hasNext()、currentItem()、next()三个最基本的方法。容器对象通过依赖注入传递到迭代器类中。
我们看下java里面迭代器的设计:
public interface Iterator<E> {//只粘贴核心方法
boolean hasNext();
E next();
}
//ArrayList内部类
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
}
@Slf4j
public class IteratorTest {
public static void main(String[] args) {
List<String> list=new ArrayList<>();
list.add("hello");
list.add("world");
list.add("java");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
log.info(iterator.next());
}
}
}
2-迭代器模式的优势
一般来讲,遍历集合数据有三种方法:for循环、foreach循环、iterator迭代器。
@Slf4j
public class IteratorTest {
public static void main(String[] args) {
List<String> list=new ArrayList<>();
list.add("hello");
list.add("world");
list.add("java");
// 第一种遍历方式:for循环
for (int i = 0; i < list.size(); i++) {
log.info(list.get(i));
}
log.info("*****************************");
// 第二种遍历方式:foreach循环
for (String str : list) {
log.info(str);
}
log.info("*****************************");
// 第三种遍历方式:迭代器遍历
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
log.info(iterator.next());
}
}
}
foreach循环只是一个语法糖而已,底层是基于迭代器来实现的。也就是说,上面代码中的第二种遍历方式(foreach循环代码)的底层实现,就是第三种遍历方式(迭代器遍历代码)。这两种遍历方式可以看作同一种遍历方式,也就是迭代器遍历方式。从上面的代码来看,for循环遍历方式比起迭代器遍历方式,代码看起来更加简洁。那我们为什么还要用迭代器来遍历容器呢?为什么还要给容器设计对应的迭代器呢?
迭代器模式封装集合内部的复杂数据结构,开发者不需要了解如何遍历,直接使用容器提供的迭代器即可;
迭代器模式将集合对象的遍历操作从集合类中拆分出来,放到迭代器类中,让两者的职责更加单一;
迭代器模式让添加新的遍历算法更加容易,更符合开闭原则。除此之外,因为迭代器都实现自相同的接口,在开发中,基于接口而非实现编程,替换迭代器也变得更加容易。