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


  • 相关阅读:
    火狐浏览器标签之间切换的快捷键
    LeetCode 69. x 的平方根
    LeetCode 51. N皇后
    win 10 自带 Ubuntu 系统的文件位置
    LeetCode 122. 买卖股票的最佳时机 II
    LeetCode 169. 求众数
    LeetCode 50. Pow(x, n)
    LeetCode 236. 二叉树的最近公共祖先
    LeetCode 235. 二叉搜索树的最近公共祖先
    LeetCode 98. 验证二叉搜索树
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3292315.html
Copyright © 2011-2022 走看看