迭代器模式
字数: 0

基本概念

Iterator Pattern: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
notion image
notion image

相关联系

  • 可以同时使用
    工厂模式
    模式和迭代器来让子类集合返回不同类型的迭代器。

实现代码

迭代器

声明一个或多个方法来获取与集合兼容的迭代器。 返回方法的类型必须被声明为迭代器接口, 因此具体集合可以返回各种不同种类的迭代器。

测试类

📌
MovieIterator 用于遍历电影列表。客户端通过该迭代器来访问电影列表,而不需要知道列表是如何存储和管理的。

Q & A

What is the use of an iterator pattern?
  • You can traverse an object structure without knowing its internal details.
  • You can provide an implementation that supports multiple traversals simultaneously.
What are the key challenges associated with this pattern?
🧻
Ideally, during a traversal/iteration process, you should not perform any accidental modification to the core architecture.
  • 利用 for-each 遍历集合的时候,实际在使用一个隐式迭代器,它的底层类似以下代码
    • Java 集合类都是利用一个快速失败(fail-fast)的迭代器。之前的 list.remove(item) 调用的是 ArrayListremove 方法,而不是迭代器的 remove 方法。那么当隐式迭代器会检测到集合结构的改变,由于该改变不是通过迭代器本身进行的,它会立即抛出异常,避免不确定的行为或不一致的结果。
    notion image
     
    2023 - 2026