Home  >  Article  >  Backend Development  >  php中的设计模式之--观察者模式_PHP教程

php中的设计模式之--观察者模式_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:05:47909browse

php中的设计模式之--观察者模式

observers[] = $observer ;
	}
	
  // 删除观察者 (看花的人)
	public function detach(Observer $observer){
		
		if(in_array($observer,$this->observers)){
			$index = array_search($observer, $this->observers);
		    unset($this->observers[$index]);
            return TRUE;
		}
		return false; 
		
	}
	
//	向观察者(们)发出通知
	public function notify(){
		
		foreach($this->observers as $observer){
			$observer->dosometing(); 
		}
	}
	
}



// 具体的人 

class LoveFlowerPerson implements Observer{
	 private $name  ;
	
	 function __construct($sName){
		 $this->name =$sName ;
	 }
	 public function dosometing(){
		 
	  echo  $this->name.'浇花  ';		
	 }
	 
}



/* 添加第一个观察者花农 */

$subject = new Flower();
$observer1 = new LoveFlowerPerson('wlt');
$subject->attach($observer1);

/* 添加第二个观察者花农 */
$observer2 = new LoveFlowerPerson('wlb');$subject->attach($observer2);$subject->notify(); // 主题变化,通知观察者echo '删除掉一个花农
'; $subject->detach($observer2);$subject->notify(); // 主题变化,通知观察者


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/962643.htmlTechArticlephp中的设计模式之--观察者模式 observers[] = $observer ;} // 删除观察者 (看花的人)public function detach(Observer $observer){if(in_array($observer,$this->observ...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn