• 一天一个设计模式(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

  • 相关阅读:
    ORM版,学生信息管理单表查询..
    回顾
    连接不上数据库
    CI缓存文件的处理和显示 研究
    php的两个符号@和&---php总会要知道的系列
    form 表单
    CI 目录下放置index.html,防止直接访问
    程序员必须知道的10大基础实用算法及其讲解
    memached 服务器lru算法
    centos 5.5 安装 lnmp
  • 原文地址:https://www.cnblogs.com/Bin-x/p/7217434.html
Copyright © 2020-2023  润新知