设计模式之迭代器模式

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


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





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值