首页 > 代码库 > 观察者模式

观察者模式

 

观察者模式有时也被称作发布/订阅模式,该模式用于为对象实现发布/订阅功能:一旦主体对象状态发生改变,与之关联的观察者对象会收到通知,并进行相应操作。

技术分享

 

技术分享
 1 <?php 2  3 /** 4  * 观察者接口 5  */ 6 interface ObserverInterface 7 { 8     public function update($params); 9 }10 11 /**12  * 被观察者接口13  */14 interface BeenObservedInterface15 {16     public function attach(\ObserverInterface $observer);17     public function detach(\ObserverInterface $observer);18     public function notify();19 }20 21 22 23 class Observer implements ObserverInterface24 {25     public function update($params)26     {27         $reflection = new \ReflectionClass($params);28         echo "<br/>The Button(BeenObserved) ".$reflection->getName()." has been clicked!";29     }30 }31 32 33 class BeenObserved implements BeenObservedInterface34 {35     private $_observers;36 37     public function attach(\ObserverInterface $observer)38     {39         $this->_observers[spl_object_hash($observer)] = $observer;40     }41 42     public function detach(\ObserverInterface $observer)43     {44         unset($this->_observers[spl_object_hash($observer)]);45     }46 47     public function notify()48     {49         foreach ($this->_observers as $observer) {50             $observer->update($observer);51         }52     }53 54     public function test()55     {56         $this->notify();57     }58 }59 60 61 62 $observer = new Observer();63 $observer2 = new Observer();64 $beenObserved = new BeenObserved();65 66 $beenObserved->attach($observer);67 $beenObserved->attach($observer2);68 69 $beenObserved->test();
View Code

 

观察者模式