梭净挟 发表于 2025-6-6 14:12:01

迭代器模式

迭代器(Iterator)模式属于行为型模式的一种。
迭代器就是提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。
在 Java 中,迭代器模式最常见的实现就是 java.util.Iterator 接口。我们经常在Java的集合类中使用的 Iterator 遍历,就是使用的迭代器模式。java.util.Enumeration 接口,java.util.ListIterator 接口都是迭代器模式的应用。java.util.ListIterator 接口是 Iterator 的增强版,支持双向遍历(hasPrevious()、previous())。
迭代器模式使调用者总是以相同接口遍历不同类型的集合,又保证了调用者对集合内部的数据结构一无所知。这种方式不仅对客户端来说非常方便, 而且能避免客户端在直接与集合交互时执行错误或有害的操作,从而起到保护集合的作用。
迭代器模式的主要思想是将集合的遍历行为抽取为单独的迭代器对象。
迭代器模式通常有以下组成部分: 

[*]Iterator(迭代器接口):定义访问和遍历元素的方法。
[*]ConcreteIterator(具体迭代器):实现 Iterator 接口,负责具体集合的遍历逻辑,记录遍历的位置。
[*]Aggregate(聚合接口):定义创建迭代器的方法。
[*]ConcreteAggregate(具体聚合类):实现 Aggregate 接口,提供具体集合的数据存储,并返回相应的迭代器实例。
[*]客户端(Client):使用自定义集合和迭代器。
我们创建一个简单的自定义集合类 MyCollection,以及对应的迭代器。
1、迭代器接口
// 迭代器接口
interface Iterator<T> {
    boolean hasNext(); // 是否还有下一个元素
    T next();          // 获取下一个元素
}2、聚合接口
// 聚合接口
interface Aggregate<T> {
    Iterator<T> createIterator(); // 创建迭代器
}3、自定义集合类,类中定义了迭代器内部类
// 自定义集合类
class MyCollection<T> implements Aggregate<T> {
    private T[] items;// 存储元素的数组
    private int size;   // 当前集合大小

    @SuppressWarnings("unchecked")
    public MyCollection(int capacity) {
      items = (T[]) new Object;
      size = 0;
    }

    public void add(T item) {
      if (size < items.length) {
            items = item;
      } else {
            throw new IllegalStateException("Collection is full");
      }
    }

    public int size() {
      return size;
    }

    public T get(int index) {
      if (index >= 0 && index < size) {
            return items;
      }
      throw new IndexOutOfBoundsException("Index out of bounds");
    }

    // 返回一个迭代器
    @Override
    public Iterator<T> createIterator() {
      return new MyCollectionIterator();
    }

    // 内部迭代器类
    private class MyCollectionIterator implements Iterator<T> {
      private int currentIndex = 0;

      @Override
      public boolean hasNext() {
            return currentIndex < size; // 判断是否还有元素
      }

      @Override
      public T next() {
            if (hasNext()) {
                return items; // 返回当前元素并移动指针
            }
            throw new IllegalStateException("No more elements");
      }
    }
}4、客户端
public class IteratorPatternDemo {
    public static void main(String[] args) {
      // 创建一个集合
      MyCollection<String> collection = new MyCollection<>(5);
      collection.add("A");
      collection.add("B");
      collection.add("C");
      collection.add("D");

      // 获取集合的迭代器
      Iterator<String> iterator = collection.createIterator();

      // 使用迭代器遍历集合
      while (iterator.hasNext()) {
            System.out.println(iterator.next());
      }
    }
}迭代器模式的优缺点。
优点:

[*]统一遍历接口:通过迭代器,可以使用统一的方式遍历不同集合。
[*]隐藏集合内部结构:调用者无需了解集合的实现细节,只需通过迭代器访问元素。
[*]解耦集合与遍历算法:迭代器封装了遍历逻辑,集合类只负责存储数据。
缺点:

[*]如果集合很大,创建迭代器可能会增加额外的开销。
[*]对于简单集合,使用迭代器可能显得复杂。
我们可以使用迭代器模式来遍历组合模式树。
迭代器模式是一种非常实用的设计模式,它解耦了集合对象的存储与访问逻辑,在 Java 中被广泛应用。通过迭代器,程序可以以一种简单而一致的方式操作各种集合对象,而无需关心它们的内部实现。
人生有时真的很残酷,就像在流沙里奔跑,任何一点风吹草动,都足以击垮我们的沙城。-- 烟沙九洲
​ ◀
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 迭代器模式