>  기사  >  백엔드 개발  >  디자인 패턴 소개-반복자 패턴(php 버전)

디자인 패턴 소개-반복자 패턴(php 버전)

WBOY
WBOY원래의
2016-08-08 09:27:08784검색

이 디자인 패턴을 살펴보기 전에 Niao 형제의 블로그에 있는 인터뷰 질문을 먼저 살펴보겠습니다.

질문은 다음과 같습니다.

Enable the object to be foreached 배열 루프와 마찬가지로 속성이 비공개여야 합니다.

반복자 패턴을 사용하지 않으면 구현하기 어렵습니다. 먼저 구현 코드를 살펴보겠습니다.

sample.php

<?php
class Sample implements Iterator{
	private $_arr;
	
	public function __construct(Array $arr){
		$this->_arr = $arr;
	}
	
	public function current(){
	    return current($this->_arr);
	}
	
	public function next(){
	     return next($this->_arr);
	}
	
	public function key(){
	     return key($this->_arr);
	}
	
	public function valid(){
	     return $this->current() !== false;
	}
	
	public function rewind(){
	   reset($this->_arr);
	}
}

index.php
<?php
require &#39;Sample.php&#39;;

$arr = new Sample([&#39;max&#39;, &#39;ben&#39;, &#39;will&#39;]); 

foreach ($arr as $k=>$v){
    echo $k."-".$v."<br />";
}

Iterator 인터페이스는 PHP의 spl 클래스 라이브러리에서 가져온 것입니다. 디자인 패턴에 대한 관련 기사를 작성한 후 이 클래스 라이브러리에 대해 더 자세히 연구하겠습니다.

추가로 인터넷에서 Yii 프레임워크의 반복자 패턴에 대한 구현 코드를 찾았습니다.

class CMapIterator implements Iterator {
/**
* @var array the data to be iterated through
*/
    private $_d;
/**
* @var array list of keys in the map
*/
    private $_keys;
/**
* @var mixed current key
*/
    private $_key;
 
/**
* Constructor.
* @param array the data to be iterated through
*/
    public function __construct(&$data) {
        $this->_d=&$data;
        $this->_keys=array_keys($data);
    }
 
/**
* Rewinds internal array pointer.
* This method is required by the interface Iterator.
*/
    public function rewind() {                                                                                 
        $this->_key=reset($this->_keys);
    }
 
/**
* Returns the key of the current array element.
* This method is required by the interface Iterator.
* @return mixed the key of the current array element
*/
    public function key() {
        return $this->_key;
    }
 
/**
* Returns the current array element.
* This method is required by the interface Iterator.
* @return mixed the current array element
*/
    public function current() {
        return $this->_d[$this->_key];
    }
 
/**
* Moves the internal pointer to the next array element.
* This method is required by the interface Iterator.
*/
    public function next() {
        $this->_key=next($this->_keys);
    }
 
/**
* Returns whether there is an element at current position.
* This method is required by the interface Iterator.
* @return boolean
*/
    public function valid() {
        return $this->_key!==false;
    }
}
 
$data = array('s1' => 11, 's2' => 22, 's3' => 33);
$it = new CMapIterator($data);
foreach ($it as $row) {
    echo $row, '<br />';
}

반복자 디자인 패턴의 공식 정의는 다음과 같습니다. 반복자 패턴을 사용하여 집계 개체에 대한 통합 액세스를 제공합니다. 즉, 개체의 내부 구조를 노출하지 않고 집계 개체에 액세스하고 탐색할 수 있는 외부 반복자를 제공합니다. 커서 모드라고도 합니다.

글쎄, 잘 이해가 안 가네요. foreach를 사용하여 배열을 탐색할 수 있다는 것이 분명한데 왜 이러한 반복기 모드를 사용하여 구현해야 합니까? 우리는 더 깊이 이해하기 위해 작업 경험이 깊어질 때까지만 기다릴 수 있습니다.

참고 문서:

http://www.cnblogs.com/davidhhuan/p/4248206.html

http://blog.csdn.net /hguisu/article/details/7552841

http://www.phppan.com/2010/04/php-iterator-and-yii-cmapiterator/

PHP 소스 코드 읽기 노트 24: 반복자 구현에서 값이 false일 때 반복을 완료할 수 없는 이유 분석: http://www.phppan.com/2010/04/php-source-24-iterator-false-value /


위 내용은 디자인 패턴 - 반복자 패턴(php 버전)에 대한 소개와 내용을 포함하여 PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

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