php迭代器模式(iterator pattern)

萝らか妹 提交于 2020-03-11 09:37:33

。。。

<?php
/*
The iterator pattern is used to traverse a container and access its elements. In
other words, one class becomes able to traverse the elements of another class.
The PHP has a native support for the iterator as part of built in  \Iterator and
\IteratorAggregate interfaces.
*/

class ProductIterator implements \Iterator {
    private $position = 0;
    private $productsCollection;
    
    public function __construct(ProductCollection 
        $productsCollection) {
            $this->productsCollection = $productsCollection;
        }
        
    public function current() {
        return $this->productsCollection->
            getProduct($this->position);
    }
    
    public function key() {
        return $this->position;
    }
    
    public function next() {
        $this->position++;
    }
    
    public function rewind() {
        $this->position = 0;
    }
    
    public function valid() {
        return !is_null($this->productsCollection->
            getProduct($this->position));
    }
}

class ProductCollection implements \IteratorAggregate {
    private $products = array();
    
    public function getIterator() {
        return new ProductIterator($this);
    }
    
    public function addProduct($string) {
        $this->products[] = $string;
    }
    
    public function getProduct($key) {
        if (isset($this->products[$key])) {
            return $this->products[$key];
        }
        return null;
    }
    
    public function isEmpty() {
        return empty($products);
    }
}

$products = new ProductCollection();
$products->addProduct('T-Shirt Red<br/>');
$products->addProduct('T-Shirt Blue<br/>');
$products->addProduct('T-Shirt Green<br/>');
$products->addProduct('T-Shirt Yellow<br/>');

foreach ($products as $product) {
    var_dump($product);
}
?>

输出:

string(16) "T-Shirt Red
" string(17) "T-Shirt Blue
" string(18) "T-Shirt Green
" string(19) "T-Shirt Yellow
"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!