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; }}
被观察者:实现标准接口类库splobserver。一个update方法。
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