zoukankan      html  css  js  c++  java
  • 一天一个设计模式(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

  • 相关阅读:
    工作感悟
    9/10记事
    总结几份工作的感悟
    四次原则
    在UC浏览器上很炫的一个效果
    php跨服务器传递对象
    wdlinux一键安装包
    手机号码4位隐藏
    php中英文字符串转字母转大小写
    MySQL添加用户、删除用户与授权
  • 原文地址:https://www.cnblogs.com/Bin-x/p/7217434.html
Copyright © 2011-2022 走看看