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();
    }
  • 相关阅读:
    Portable Executable 可移植可执行
    汇编跳转指令
    Java中this和super
    Java成员变量和类变量
    EasyUI select
    JAVA虚函数
    感想
    函数
    ueditor
    gitlab简介配置和参数修改
  • 原文地址:https://www.cnblogs.com/zhouqi666/p/9156580.html
Copyright © 2011-2022 走看看