php观察者模式入门例子

WBOY
發布: 2016-07-25 08:52:08
原創
866 人瀏覽過
  1. class DemoSubject implements SplSubject{
  2.     private $observers, $value;
  3.     public function __construct(){
  4.         $this->observers = array();
  5.     }
  6.     public function attach(SplObserver $observer){
  7.         $this->observers[] = $observer;
  8.     }
  9.     public function detach(SplObserver $observer){
  10.         if($idx = array_search($observer, $this->observers, true)){
  11.             unset($this->observers[$idx]);
  12.         }
  13.     }
  14.     public function notify(){
  15.         foreach($this->observers as $observer){
  16.             $observer->update($this);
  17.         }
  18.     }
  19.     public function setValue($value){
  20.         $this->value = $value;
  21.         $this->notify();
  22.     }
  23.     public function getValue(){
  24.         return $this->value;
  25.     }
  26. }
  27. class DemoObserver implements SplObserver{
  28.     public function update(SplSubject $subject){
  29.         echo 'The new value is '. $subject->getValue();
  30.     }
  31. }
  32. $subject = new DemoSubject();
  33. $observer = new DemoObserver();
  34. $subject->attach($observer);
  35. $subject->setValue(5);
复制代码


來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!