• 设计模式之迭代器模式


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


  • 相关阅读:
    定义字符串数组
    ifconfig 修改IP
    空指针与野指针的区别
    GDB和Core Dump使用笔记
    雅虎(ycsb)测试hbase(压测)
    decode函数的几种用法
    NVL函数:空值转换函数
    hive行转列,列转行
    case when then else end用法
    hive中一般取top n时,row_number(),rank,dense_ran()常用三个函数
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3292315.html
Copyright © 2020-2023  润新知