zoukankan      html  css  js  c++  java
  • 设计模式之迭代器模式

    <?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 "
    ";
    }
    
    
    
    
    


  • 相关阅读:
    Intellij 常用技巧-持续更新
    Android界面组件的四种启动方式
    Preference Screen 首选项
    Oracle OCI-22053:溢出错误
    SQLPLUS使用
    Oracle中数字格式的文本化处理
    MP4V2 移植 (基于imx6 平台)
    IMX6Q camera 应用编程之 摄像头裁剪
    IMX6Q camera驱动分析 (4)
    IMX6Q Camera驱动分析 (3)
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3292315.html
Copyright © 2011-2022 走看看