zoukankan      html  css  js  c++  java
  • 设计模式之迭代器模式(PHP实现)

    github地址:https://github.com/ZQCard/design_pattern
    /*
    * * 迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式。 * 这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。迭代器模式属于行为型模式。 */

    (1)Iterator.class.php(接口)

    <?php
    
    namespace Iterator;
    
    interface Iterator
    {
        public function First();
        public function Next();
        public function IsDone();
        public function CurrentItem();
    }

    (2) ConcreteIteratior.class.php

    <?php
    
    namespace Iterator;
    
    class ConcreteIterator implements Iterator{
        private $_users;
    
        private $_current = 0;
    
        public function __construct(array $users)
        {
            $this->_users = $users;
        }
    
        public function First()
        {
            return $this->_users[0];
        }
    
        //返回下一个
        public function  Next()
        {
            $this->_current++;
            if($this->_current<count($this->_users))
            {
                return $this->_users[$this->_current];
            }
            return false;
        }
    
        //返回是否IsDone
        public function IsDone()
        {
            return $this->_current>=count($this->_users)?true:false;
        }
    
        //返回当前聚集对象
        public function CurrentItem()
        {
            return $this->_users[$this->_current];
        }
    }

    (3)iterator.php (客户端)

    <?php
    spl_autoload_register(function ($className){
        $className = str_replace('\','/',$className);
        include $className.".class.php";
    });
    
    use IteratorConcreteIterator;
    
    $iterator= new ConcreteIterator(array('周杰伦','王菲','周润发'));
    $item = $iterator->First();
    echo $item."<br/>";
    while(!$iterator->IsDone())
    {
        echo "{$iterator->CurrentItem()}:请买票!<br/>";
        $iterator->Next();
    }
  • 相关阅读:
    【POJ】【2420】A Star not a Tree?
    【BZOJ】【2818】Gcd
    【BZOJ】【2190】【SDOI2008】仪仗队
    【Vijos】【1164】曹冲养猪
    【BZOJ】【1430】小猴打架
    【BZOJ】【3611】【HEOI2014】大工程
    【转载】完全图的生成树
    【BZOJ】【2286】【SDOI2011】消耗战
    【POJ】【1061】/【BZOJ】【1477】青蛙的约会
    Codeforces VK Cup Finals #424 Div.1 A. Office Keys(DP)
  • 原文地址:https://www.cnblogs.com/zhouqi666/p/9156580.html
Copyright © 2011-2022 走看看