观察者模式

 

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

 

 1 <?php
 2 
 3 /**
 4  * 观察者接口
 5  */
 6 interface ObserverInterface
 7 {
 8     public function update($params);
 9 }
10 
11 /**
12  * 被观察者接口
13  */
14 interface BeenObservedInterface
15 {
16     public function attach(\ObserverInterface $observer);
17     public function detach(\ObserverInterface $observer);
18     public function notify();
19 }
20 
21 
22 
23 class Observer implements ObserverInterface
24 {
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 BeenObservedInterface
34 {
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

 

posted @ 2017-01-08 19:40  _logan  阅读(130)  评论(0编辑  收藏  举报