• 设计模式之迭代器模式


    <?php
    /**
    迭代器模式
    
    迭代的使用任何数据类型的数据
    
    php提供了两个接口
    **/
    
    
    /**
     * Interator在内部迭代自己的类的接口
     *
     * Iterator extends Traversable {
            abstract public mixed current ( void )
            abstract public scalar key ( void )
            abstract public void next ( void )
            abstract public void rewind ( void )
            abstract public boolean valid ( void )
        }
    
     *
     */
    
    
    /*
     * IteratorAggregate  创建外部迭代器的接口
     *
     * IteratorAggregate extends Traversable {
            abstract public Traversable getIterator ( void )
        }
     *
     *
     *
     *
     */
    
    class A{
        private $_name;
        public function __construct($name){
            $this->_name = $name;
        }
    }
    
    class myIterator implements Iterator
    {
        private $_p;
        private $_data;
    
        public function __construct(){
            $this->_data = array(new A("apple"), new A("banana"), new A("blow"));
            $this->_p = 0;
        }
    
        public function current()
        {
            return array_key_exists($this->_p, $this->_data)
                    ? $this->_data[$this->_p] : false;
        }
        public function key()
        {
            return $this->_p;
        }
        public function next()
        {
            $this->_p++;
        }
    
        public function rewind()
        {
            $this->_p = 0;
        }
        public function valid()
        {
            return array_key_exists($this->_p, $this->_data);
        }
    }
    
    $test = new myIterator();
    
    foreach ($test as $key => $value){
        echo "$key => ";
        var_dump($value);
        echo "
    ";
    }
    
    
    class myIterator2 implements IteratorAggregate
    {
        private $_data;
    
        public function __construct()
        {
            $this->_data = array(new A("apple"), new A("banana"), new A("blow"));
        }
    
        public function getIterator()
        {
            //if $this->_data change with $this it will iterator the property
            return new ArrayIterator($this->_data);
        }
    }
    $test = new myIterator2();
    
    foreach ($test as $key => $value){
        echo "$key => ";
        var_dump($value);
        echo "
    ";
    }
    
    
    
    
    


  • 相关阅读:
    uva 12034 Race
    计算机基础之计算机硬件软件数据结构
    Project Perfect让Swift在server端跑起来-Perfect in Visual Studio Code (四)
    关于自己定义转场动画,我都告诉你。
    Shell编程入门
    CODEVS 1029 遍历问题
    【VBA研究】工作表自己主动筛选模式检測
    卸载MySQL 5.0
    操作系统(二)进程控制
    前端面试题
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3292315.html
Copyright © 2020-2023  润新知