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();
    }
  • 相关阅读:
    字段与表的对应关系
    java初学代码,还不太熟练
    编程学习心得
    ps中经常遇到的问题
    R语言矩阵运算加速
    写代码过程中一些数字推理公式
    EXCEL中常用的函数
    css样式中常见的属性
    R语言的基本矩阵运算
    excel常用的函数
  • 原文地址:https://www.cnblogs.com/zhouqi666/p/9156580.html
Copyright © 2011-2022 走看看