背景

在现实生活以及程序设计中,经常要访问一个聚合对象中的各个元素,如“数据结构”中的链表遍历,通常的做法是将链表的创建和遍历都放在同一个类中,但这种方式不利于程序的扩展,如果要更换遍历方法就必须修改程序源代码,这违背了 “开闭原则”。

既然将遍历方法封装在聚合类中不可取,那么聚合类中不提供遍历方法,将遍历方法由用户自己实现是否可行呢?答案是同样不可取,因为这种方式会存在两个缺点:

  1. 暴露了聚合类的内部表示,使其数据不安全;
  2. 增加了客户的负担。

“迭代器模式”能较好地克服以上缺点,它在客户访问类与聚合类之间插入一个迭代器,这分离了聚合对象与其遍历行为,对客户也隐藏了其内部细节,且满足“单一职责原则”和“开闭原则”,如 Java 中的 Collection、List、Set、Map 等都包含了迭代器。

应用

迭代器模式在生活中应用的比较广泛,比如:物流系统中的传送带,不管传送的是什么物品,都会被打包成一个个箱子,并且有一个统一的二维码。这样我们不需要关心箱子里是什么,在分发时只需要一个个检查发送的目的地即可。再比如,我们平时乘坐交通工具,都是统一刷卡或者刷脸进站,而不需要关心是男性还是女性、是残疾人还是正常人等信息。

模式的定义与特点

迭代器(Iterator)模式的定义:提供一个对象来顺序访问聚合对象中的一系列数据,而不暴露聚合对象的内部表示。迭代器模式是一种对象行为型模式,其主要优点如下。

  1. 访问一个聚合对象的内容而无须暴露它的内部表示。
  2. 遍历任务交由迭代器完成,这简化了聚合类。
  3. 它支持以不同方式遍历一个聚合,甚至可以自定义迭代器的子类以支持新的遍历。
  4. 增加新的聚合类和迭代器类都很方便,无须修改原有代码。
  5. 封装性良好,为遍历不同的聚合结构提供一个统一的接口。

其主要缺点是:增加了类的个数,这在一定程度上增加了系统的复杂性。

在日常开发中,我们几乎不会自己写迭代器。除非需要定制一个自己实现的数据结构对应的迭代器,否则,开源框架提供的 API 完全够用

模式的结构与实现迭代器模式是通过将聚合对象的遍历行为分离出来,抽象成迭代器类来实现的,其目的是在不暴露聚合对象的内部结构的情况下,让外部代码透明地访问聚合的内部数据。现在我们来分析其基本结构与实现方法。

1. 模式的结构

迭代器模式主要包含以下角色。

  1. 抽象聚合(Aggregate)角色:定义存储、添加、删除聚合对象以及创建迭代器对象的接口。
  2. 具体聚合(ConcreteAggregate)角色:实现抽象聚合类,返回一个具体迭代器的实例。
  3. 抽象迭代器(Iterator)角色:定义访问和遍历聚合元素的接口,通常包含 hasNext()、first()、next() 等方法。
  4. 具体迭代器(Concretelterator)角色:实现抽象迭代器接口中所定义的方法,完成对聚合对象的遍历,记录遍历的当前位置。

    1. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/685018/1620721655953-14f3f734-72d7-47cc-8be9-e4685a9f6df5.png#align=left&display=inline&height=360&margin=%5Bobject%20Object%5D&name=image.png&originHeight=360&originWidth=500&size=39235&status=done&style=none&width=500)

    2.实现

    ```php <?php

//迭代 class AlphabeticalOrderIterator implements \Iterator { private $collection;

  1. private $position = 0;
  2. private $reverse = false;
  3. public function __construct($collection, $reverse = false)
  4. {
  5. $this->collection = $collection;
  6. $this->reverse = $reverse;
  7. }
  8. public function rewind()
  9. {
  10. $this->position = $this->reverse ? count($this->collection->getItems()) - 1 : 0;
  11. }
  12. public function current()
  13. {
  14. return $this->collection->getItems()[$this->position];
  15. }
  16. public function key()
  17. {
  18. return $this->position;
  19. }
  20. public function next()
  21. {
  22. $this->position = $this->position + ($this->reverse ? -1 : 1);
  23. }
  24. public function valid()
  25. {
  26. return isset($this->collection->getItems()[$this->position]);
  27. }

}

//聚合 class WordsCollection implements \IteratorAggregate { private $items = [];

  1. public function getItems()
  2. {
  3. return $this->items;
  4. }
  5. public function addItem($item)
  6. {
  7. $this->items[] = $item;
  8. }
  9. public function getIterator(): Iterator
  10. {
  11. return new AlphabeticalOrderIterator($this);
  12. }
  13. public function getReverseIterator(): Iterator
  14. {
  15. return new AlphabeticalOrderIterator($this, true);
  16. }

}

$aa = new WordsCollection(); $aa->addItem(‘11’); $aa->addItem(‘22’); $aa->addItem(‘33’);

echo ‘正序’.PHP_EOL;; foreach ($aa->getIterator() as $item){ echo $item.PHP_EOL; }

echo ‘倒序’.PHP_EOL;

foreach ($aa->getReverseIterator() as $item) { echo $item.PHP_EOL; }

  1. 输出
  2. ```php
  3. 正序
  4. 11
  5. 22
  6. 33
  7. 倒序
  8. 33
  9. 22
  10. 11

读取csv

  1. <?php
  2. class CsvIterator implements \Iterator
  3. {
  4. const ROW_SIZE = 4096;
  5. /**
  6. * The pointer to the CSV file.
  7. *
  8. * @var resource
  9. */
  10. protected $filePointer = null;
  11. /**
  12. * The current element, which is returned on each iteration.
  13. *
  14. * @var array
  15. */
  16. protected $currentElement = null;
  17. /**
  18. * The row counter.
  19. *
  20. * @var int
  21. */
  22. protected $rowCounter = null;
  23. /**
  24. * The delimiter for the CSV file.
  25. *
  26. * @var string
  27. */
  28. protected $delimiter = null;
  29. /**
  30. * The constructor tries to open the CSV file. It throws an exception on
  31. * failure.
  32. *
  33. * @param string $file The CSV file.
  34. * @param string $delimiter The delimiter.
  35. *
  36. * @throws \Exception
  37. */
  38. public function __construct($file, $delimiter = ',')
  39. {
  40. try {
  41. $this->filePointer = fopen($file, 'rb');
  42. $this->delimiter = $delimiter;
  43. } catch (\Exception $e) {
  44. throw new \Exception('The file "' . $file . '" cannot be read.');
  45. }
  46. }
  47. /**
  48. * This method resets the file pointer.
  49. */
  50. public function rewind(): void
  51. {
  52. $this->rowCounter = 0;
  53. rewind($this->filePointer);
  54. }
  55. /**
  56. * This method returns the current CSV row as a 2-dimensional array.
  57. *
  58. * @return array The current CSV row as a 2-dimensional array.
  59. */
  60. public function current(): array
  61. {
  62. $this->currentElement = fgetcsv($this->filePointer, self::ROW_SIZE, $this->delimiter);
  63. $this->rowCounter++;
  64. return $this->currentElement;
  65. }
  66. /**
  67. * This method returns the current row number.
  68. *
  69. * @return int The current row number.
  70. */
  71. public function key(): int
  72. {
  73. return $this->rowCounter;
  74. }
  75. /**
  76. * This method checks if the end of file has been reached.
  77. *
  78. * @return bool Returns true on EOF reached, false otherwise.
  79. */
  80. public function next(): bool
  81. {
  82. if (is_resource($this->filePointer)) {
  83. return !feof($this->filePointer);
  84. }
  85. return false;
  86. }
  87. /**
  88. * This method checks if the next row is a valid row.
  89. *
  90. * @return bool If the next row is a valid row.
  91. */
  92. public function valid(): bool
  93. {
  94. if (!$this->next()) {
  95. if (is_resource($this->filePointer)) {
  96. fclose($this->filePointer);
  97. }
  98. return false;
  99. }
  100. return true;
  101. }
  102. }
  103. /**
  104. * The client code.
  105. */
  106. $csv = new CsvIterator(__DIR__ . '/student.csv');
  107. foreach ($csv as $key => $row) {
  108. print_r($row);
  109. }

student.csv

  1. zhanglibin,23,男
  2. long,24,女
  3. ko,33,妖

输出

  1. Array
  2. (
  3. [0] => zhanglibin
  4. [1] => 23
  5. [2] =>
  6. )
  7. Array
  8. (
  9. [0] => long
  10. [1] => 24
  11. [2] =>
  12. )
  13. Array
  14. (
  15. [0] => ko
  16. [1] => 33
  17. [2] =>
  18. )