在面向对象程序设计中,迭代器模式是一种设计模式,其中迭代器用于遍历容器并访问容器的元素。迭代器模式将算法与容器解耦; 在某些情况下,算法是特定容器必需的,因此不能解耦。
<?php class RadioStation { private $_frequency; public function __construct(float $frequency) { $this->_frequency = $frequency; } public function getFrequency(): float { return $this->_frequency; } } class StationList implements Countable, Iterator { private $_stations = []; private $_counter; public function addStation(RadioStation $station) { $this->_stations[] = $station; } public function removeStation(RadioStation $station) { $key=array_search($station,$this->_stations); array_splice($this->_stations,$key,1); } public function count(): int { return count($this->_stations); } public function current() { return $this->_stations[$this->_counter]; } public function next() { $this->_counter++; } public function key() { return $this->_counter; } public function valid() { return isset($this->_stations[$this->_counter]); } public function rewind() { $this->_counter = 0; } } $stationList=new StationList(); $stationList->addStation(new RadioStation(88)); $stationList->addStation(new RadioStation(89)); $stationList->addStation(new RadioStation(90)); $stationList->addStation(new RadioStation(91)); $stationList->removeStation(new RadioStation(89)); foreach ($stationList as $station){ echo $station->getFrequency().PHP_EOL; }