简介
提供一种办法程序拜访一个聚合对象中的各个元素,而又不须要裸露该对象的外部示意。
角色
- Iterator 形象迭代器
- Collection 形象汇合
- ConcreteIterator 具体迭代器
- ConcreteCollection 具体汇合
类图
如图,Iterator 和 IterableCollection 定义了操作接口,ConcreteIterator 实现类持有 ConcreteCollection 的援用,默默实现迭代的逻辑。
代码
use Iterator;
class AlphabeticalOrderIterator implements \Iterator
{
private $collection;
private $position = 0;
private $reverse = false;
public function __construct($collection, $reverse = false)
{
$this->collection = $collection;
$this->reverse = $reverse;
}
public function rewind()
{
$this->position = $this->reverse ?
count($this->collection->getItems()) - 1 : 0;
}
public function current()
{return $this->collection->getItems()[$this->position];
}
public function key()
{return $this->position;}
public function next()
{$this->position = $this->position + ($this->reverse ? -1 : 1);
}
public function valid()
{return isset($this->collection->getItems()[$this->position]);
}
}
class WordsCollection implements \IteratorAggregate
{private $items = [];
public function getItems()
{return $this->items;}
public function addItem($item)
{$this->items[] = $item;
}
public function getIterator(): Iterator
{return new AlphabeticalOrderIterator($this);
}
public function getReverseIterator(): Iterator
{return new AlphabeticalOrderIterator($this, true);
}
}
$collection = new WordsCollection();
$collection->addItem("First");
$collection->addItem("Second");
$collection->addItem("Third");
echo "Straight traversal:\n";
foreach ($collection->getIterator() as $item) {echo $item . "\n";}
echo "\n";
echo "Reverse traversal:\n";
foreach ($collection->getReverseIterator() as $item) {echo $item . "\n";}
output:
Straight traversal:
First
Second
Third
Reverse traversal:
Third
Second
First
本文由 mdnice 多平台公布