时间:2021-07-01 10:21:17 帮助过:41人阅读
PHP的观察者设计模式实现相对简单,但是PHP5+版本中已经有标准库类库支持,我们只需简单继承并实现就可以了。
观察者:实现标准接口类库SplSubject。一个注册方法:attach,一个取消注册方法:detach。一个通知方法:nofity。
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;
}
}
getValue(); } }
getValue(); } }
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
http://www.bkjia.com/PHPjc/875469.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/875469.htmlTechArticlePHP5+标准函数库观察者之实现 PHP的观察者设计模式实现相对简单,但是PHP5版本中已经有标准库类库支持,我们只需简单继承并实现就可以了...