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