<?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";
}
设计模式之迭代器模式
最新推荐文章于 2024-01-23 15:46:15 发布