迭代器模式
约 438 字大约 1 分钟
2025-07-08
<?php
// 迭代器接口
interface IteratorInterface {
public function hasNext();
public function next();
}
// 集合接口
interface Aggregate {
public function createIterator();
}
// 具体迭代器类
class ConcreteIterator implements IteratorInterface {
private $collection;
private $position = 0;
public function __construct(array $collection) {
$this->collection = $collection;
}
public function hasNext() {
return $this->position < count($this->collection);
}
public function next() {
$element = $this->collection[$this->position];
$this->position++;
return $element;
}
}
// 具体集合类
class ConcreteAggregate implements Aggregate {
private $collection = [];
public function addItem($item) {
$this->collection[] = $item;
}
public function createIterator() {
return new ConcreteIterator($this->collection);
}
}
// 客户端代码
$aggregate = new ConcreteAggregate();
$aggregate->addItem("Item 1");
$aggregate->addItem("Item 2");
$aggregate->addItem("Item 3");
$iterator = $aggregate->createIterator();
while ($iterator->hasNext()) {
echo $iterator->next() . "<br>";
}
在这个示例中,IteratorInterface 定义了迭代器的基本方法,包括 hasNext() 和 next()。Aggregate 接口定义了集合类应该实现的方法,包括 createIterator()。ConcreteIterator 是具体的迭代器类,实现了迭代器接口,负责在集合上进行迭代。ConcreteAggregate 是具体的集合类,实现了集合接口,负责管理集合中的元素。在客户端代码中,我们首先创建了一个具体的集合对象 ConcreteAggregate,然后添加了一些元素。接着,我们通过调用 createIterator() 方法获得迭代器对象,并使用迭代器遍历集合中的元素。
迭代器模式的主要优点在于:
- 将集合类和遍历方式解耦,使得集合类的变化不会影响到遍历方式,反之亦然。
- 提供了一种统一的访问集合元素的方式,使得客户端代码可以更加简洁和灵活。
在这个示例中,如果我们需要改变集合的内部表示方式,例如从数组改为链表,我们只需修改 ConcreteAggregate 类的实现,而不需要修改客户端代码。