PHP5+标准函数库观察者之实现

WBOY
풀어 주다: 2016-06-23 13:50:16
원래의
932명이 탐색했습니다.

PHP的观察者设计模式实现相对简单,但是PHP5+版本中已经有标准库类库支持,我们只需简单继承并实现就可以了。

观察者:实现标准接口类库SplSubject。一个注册方法:attach,一个取消注册方法:detach。一个通知方法:nofity。

<?phpclass TSPLSubject implements SplSubject{	 private $observers, $value;	 public function __construct(){		$this->observers =array();	 }	 public function attach(SplObserver $observer){		$this->observers[] = $observer;	 }	 public function detach(SplObserver $observer){		if($idx = array_search($observer, $this->observers,true)) {			unset($this->observers[$idx]);		}	 }	     /**	 *	 * Notify observers one by one (main entry)	 *	 * @param none	 * @return none	 */	 public function notify(){		foreach($this->observers as $observer){			$observer->update($this);		}	 }	 public function setValue($value){		$this->value = $value;		//$this->notify();	 }	 public function getValue(){		 return $this->value;	 }}
로그인 후 복사

被观察者:实现标准接口类库SplObserver。一个update方法。

<?phpclass TSPLObserver implements SplObserver{	 public function update(SplSubject $subject){		 echo 'The new state of subject ' , nl2br("\r\n");//		 echo 'The new state of subject '.$subject->getValue();	 }}
로그인 후 복사
<?phpclass TSPLObserver1 implements SplObserver{	 public function update(SplSubject $subject){		 echo 'The new state of subject one ' , nl2br("\r\n");//		 echo 'The new state of subject '.$subject->getValue();	 }}
로그인 후 복사


测试调用(同目录下):

<?phpfunction __autoload($classname) {   require_once ($classname . ".php"); }$subject = new TSPLSubject();$subject->attach(new TSPLObserver());$observer1 = new TSPLObserver1();$subject->attach($observer1);//$subject->attach(new TSPLObserver2());//$subject->detach($observer1);$subject->notify();exit();
로그인 후 복사

输出:

>php basic.php
The new state of subject

The new state of subject one

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!