一天一个设计模式(14)——迭代器模式
在面向对象程序设计中,迭代器模式是一种设计模式,其中迭代器用于遍历容器并访问容器的元素。迭代器模式将算法与容器解耦; 在某些情况下,算法是特定容器必需的,因此不能解耦。
<?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; }
本文来自博客园,作者:Bin_x,转载请注明原文链接:https://www.cnblogs.com/Bin-x/p/7217434.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)