找回密码
 立即注册
首页 业界区 业界 迭代器模式

迭代器模式

梭净挟 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、迭代器接口
  1. // 迭代器接口
  2. interface Iterator<T> {
  3.     boolean hasNext(); // 是否还有下一个元素
  4.     T next();          // 获取下一个元素
  5. }
复制代码
1.gif
2、聚合接口
  1. // 聚合接口
  2. interface Aggregate<T> {
  3.     Iterator<T> createIterator(); // 创建迭代器
  4. }
复制代码
2.gif
3、自定义集合类,类中定义了迭代器内部类
  1. // 自定义集合类
  2. class MyCollection<T> implements Aggregate<T> {
  3.     private T[] items;  // 存储元素的数组
  4.     private int size;   // 当前集合大小
  5.     @SuppressWarnings("unchecked")
  6.     public MyCollection(int capacity) {
  7.         items = (T[]) new Object[capacity];
  8.         size = 0;
  9.     }
  10.     public void add(T item) {
  11.         if (size < items.length) {
  12.             items[size++] = item;
  13.         } else {
  14.             throw new IllegalStateException("Collection is full");
  15.         }
  16.     }
  17.     public int size() {
  18.         return size;
  19.     }
  20.     public T get(int index) {
  21.         if (index >= 0 && index < size) {
  22.             return items[index];
  23.         }
  24.         throw new IndexOutOfBoundsException("Index out of bounds");
  25.     }
  26.     // 返回一个迭代器
  27.     @Override
  28.     public Iterator<T> createIterator() {
  29.         return new MyCollectionIterator();
  30.     }
  31.     // 内部迭代器类
  32.     private class MyCollectionIterator implements Iterator<T> {
  33.         private int currentIndex = 0;
  34.         @Override
  35.         public boolean hasNext() {
  36.             return currentIndex < size; // 判断是否还有元素
  37.         }
  38.         @Override
  39.         public T next() {
  40.             if (hasNext()) {
  41.                 return items[currentIndex++]; // 返回当前元素并移动指针
  42.             }
  43.             throw new IllegalStateException("No more elements");
  44.         }
  45.     }
  46. }
复制代码
3.gif
4、客户端
  1. public class IteratorPatternDemo {
  2.     public static void main(String[] args) {
  3.         // 创建一个集合
  4.         MyCollection<String> collection = new MyCollection<>(5);
  5.         collection.add("A");
  6.         collection.add("B");
  7.         collection.add("C");
  8.         collection.add("D");
  9.         // 获取集合的迭代器
  10.         Iterator<String> iterator = collection.createIterator();
  11.         // 使用迭代器遍历集合
  12.         while (iterator.hasNext()) {
  13.             System.out.println(iterator.next());
  14.         }
  15.     }
  16. }
复制代码
4.gif
迭代器模式的优缺点。
优点:

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

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

相关推荐

您需要登录后才可以回帖 登录 | 立即注册