>  기사  >  백엔드 개발  >  PHP 디자인 패턴 반복자 패턴

PHP 디자인 패턴 반복자 패턴

高洛峰
高洛峰원래의
2016-11-21 14:13:531115검색

개념

Iterator 모드(Iterator), 커서(Cursor) 모드라고도 합니다. 개체의 내부 표현을 노출하지 않고 집계 개체의 다양한 요소에 순차적으로 액세스하는 방법을 제공합니다.

집합 개체에 액세스해야 하고 해당 개체가 무엇이든 이를 순회해야 하는 경우 반복자 패턴 사용을 고려해야 합니다. 또한 여러 방법으로 컬렉션을 순회해야 하는 경우 반복자 패턴 사용을 고려할 수 있습니다. 반복자 패턴은 시작, 다음, 종료 여부 및 현재 항목과 같은 다양한 컬렉션 구조를 탐색하기 위한 통합 인터페이스를 제공합니다.

적용 가능한 시나리오

내부 표현을 노출하지 않고 집계 개체의 콘텐츠에 액세스

집계 개체의 다중 순회 지원

순회에 따라 다름 집계 구조 통합 인터페이스 제공

UML 다이어그램

PHP 디자인 패턴 반복자 패턴

역할

Iterator: Iterator는 액세스 및 순회 요소의 인터페이스를 정의합니다.

ConcreteIterator (특정 반복자): 특정 반복자는 반복자 인터페이스를 구현하여 집계를 순회할 때 현재 위치를 추적합니다.

Aggregate(집계): 집계 정의는 해당 반복자 객체를 생성합니다. 인터페이스

ConcreteAggregate(콘크리트) aggregation): 구체적인 집계는 해당 반복자를 생성하는 인터페이스를 구현합니다. 이 작업은 ConcreteIterator

코드

코드는 다음과 같습니다.

PHP SPL 이미 반복자 인터페이스 Iterator와 컨테이너 인터페이스 IteatorAggragate를 제공합니다. 소스 코드는 다음과 같습니다.

/**
 * Interface to detect if a class is traversable using &foreach;.
 * @link http://php.net/manual/en/class.traversable.php
 */
interface Traversable {
}

/**
 * Interface to create an external Iterator.
 * @link http://php.net/manual/en/class.iteratoraggregate.php
 */
interface IteratorAggregate extends Traversable {

    /**
     * Retrieve an external iterator
     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
     * @return Traversable An instance of an object implementing <b>Iterator</b> or
     * <b>Traversable</b>
     * @since 5.0.0
     */
    public function getIterator();
}

/**
 * Interface for external iterators or objects that can be iterated
 * themselves internally.
 * @link http://php.net/manual/en/class.iterator.php
 */
interface Iterator extends Traversable {

    /**
     * Return the current element
     * @link http://php.net/manual/en/iterator.current.php
     * @return mixed Can return any type.
     * @since 5.0.0
     */
    public function current();

    /**
     * Move forward to next element
     * @link http://php.net/manual/en/iterator.next.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function next();

    /**
     * Return the key of the current element
     * @link http://php.net/manual/en/iterator.key.php
     * @return mixed scalar on success, or null on failure.
     * @since 5.0.0
     */
    public function key();

    /**
     * Checks if current position is valid
     * @link http://php.net/manual/en/iterator.valid.php
     * @return boolean The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     * @since 5.0.0
     */
    public function valid();

    /**
     * Rewind the Iterator to the first element
     * @link http://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function rewind();
}

여기서는 위의 두 인터페이스를 직접 구현합니다. 다음 코드를 참조하세요.

<?php
header(&#39;Content-type:text/html;charset=utf-8&#39;);
/**
 * 迭代器模式
 */

/**
 * Class ConcreteIterator 具体的迭代器
 */
class ConcreteIterator implements Iterator
{
    private $position = 0;
    private $array = array();

    public function __construct($array) {
        $this->array = $array;
        $this->position = 0;
    }

    function rewind() {
        $this->position = 0;
    }

    function current() {
        return $this->array[$this->position];
    }

    function key() {
        return $this->position;
    }

    function next() {
        ++$this->position;
    }

    function valid() {
        return isset($this->array[$this->position]);
    }
}

/**
 * Class MyAggregate 聚合容器
 */
class ConcreteAggregate implements IteratorAggregate
{
    public $property;

    /**
     * 添加属性
     *
     * @param $property
     */
    public function addProperty($property)
    {
        $this->property[] = $property;
    }

    public function getIterator()
    {
        return new ConcreteIterator($this->property);
    }
}

/**
 * Class Client 客户端测试
 */
class Client
{
    public static function test()
    {
        //创建一个容器
        $concreteAggregate = new ConcreteAggregate();
        // 添加属性
        $concreteAggregate->addProperty(&#39;属性1&#39;);
        // 添加属性
        $concreteAggregate->addProperty(&#39;属性2&#39;);
        //给容器创建迭代器
        $iterator = $concreteAggregate->getIterator();
        //遍历
        while($iterator->valid())
        {
            $key   = $iterator->key();
            $value = $iterator->current();
            echo &#39;键: &#39;.$key.&#39; 值: &#39;.$value.&#39;<hr>&#39;;
            $iterator->next();
        }

    }
}

Client:: test();

실행 결과:

키: 0 값: 속성 1
키: 1 값: 속성 2


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:PHP 이미지 업로드다음 기사:PHP 이미지 업로드