参考文献

迭代器模式

  • 迭代器模式的思想是负责访问和传递集合的对象并将其放入迭代器对象中.迭代器对象将维护迭代的状态,跟踪当前项并具有识别下一个要迭代的元素的方法.
  • 提供一种顺序访问聚合对象的元素而不暴露其底层表示的方法.
  • 迭代器模式提供的抽象允许您修改集合实现,而无需在集合之外进行任何更改

组件

  • Iterator(迭代器) : 负责定义按顺序逐个遍历元素的接口.
  • ConcreteIterator(具体的迭代器) : 负责实现Iterator角色所定义的接口
  • Collection(集合) : 负责定义创建Iterator角色的接口.
  • ConcreteCollection(具体的集合) : 负责实现Collection角色所定义的接口.

实现方式

  • 声明迭代器接口(Iterator Interface):该接口定义了获取集合中下一个元素的方法,通常命名为next();同时可以添加其他方法,比如获取前一个元素、记录当前位置和判断迭代是否结束等.

    1
    2
    3
    4
    5
    6
    public interface Iterator {
    // 用于判断是否存在下一个元素
    boolean hasNext();
    // 用于获取该元素,返回当前元素,并指向下一个元素
    Object next();
    }
  • 声明集合接口(Collection Interface):该接口描述了获取迭代器的方法,通常命名为createIterator(),返回值为迭代器接口类型.如果需要多组不同类型的迭代器,可以声明多个类似的方法.

    1
    2
    3
    public interface Collection {
    Iterator createIterator();
    }
  • 实现具体迭代器类(Concrete Iterator Class):为需要进行遍历的集合实现具体的迭代器类.迭代器对象与单个集合实例相关联.通常使用构造函数来建立链接关系.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    public class ConcreteIterator implements Iterator {
    private Object[] items;
    private int position = 0;

    public ConcreteIterator(Object[] items) {
    this.items = items;
    }

    public boolean hasNext() {
    return position < items.length;
    }

    public Object next() {
    Object currentItem = items[position];
    position++;
    return currentItem;
    }
    }
  • 在集合类中实现集合接口(Implement Collection Interface in Collection Class):集合类实现了集合接口,并提供了创建迭代器的快捷方式.集合对象在创建迭代器时会将自身传递给迭代器的构造函数,建立两者之间的链接关系.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public class ConcreteCollection implements Collection {
    private Object[] items;

    public ConcreteCollection(Object[] items) {
    this.items = items;
    }

    public Iterator createIterator() {
    return new ConcreteIterator(items);
    }
    }
  • 替换集合遍历代码(Replace Collection Traversal Code):检查客户端代码,使用迭代器替代所有的集合遍历代码.每当客户端需要遍历集合元素时,都需要获取一个新的迭代器.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public class Client {
    public static void main(String[] args) {
    Object[] items = { "Item 1", "Item 2", "Item 3" };
    Collection collection = new ConcreteCollection(items);
    Iterator iterator = collection.createIterator();

    while (iterator.hasNext()) {
    Object item = iterator.next();
    System.out.println(item);
    }
    }
    }

使用场景

  • 当集合背后为复杂的数据结构, 且你希望对客户端隐藏其复杂性时 (出于使用便利性或安全性的考虑), 可以使用迭代器模式.
  • 使用该模式可以减少程序中重复的遍历代码.
  • 如果你希望代码能够遍历不同的甚至是无法预知的数据结构, 可以使用迭代器模式.