PHP观察者模式

观察者模式(Observer),当一个对象的状态发生改变时,依赖他的对象会全部收到通知,并自动更新。

场景:一个事件发生后,要执行一连串更新操作.传统的编程方式,就是在事件的代码之后直接加入处理逻辑,当更新得逻辑增多之后,代码会变得难以维护.这种方式是耦合的,侵入式的,增加新的逻辑需要改变事件主题的代码
观察者模式实现了低耦合,非侵入式的通知与更新机制

 1 /**
 2  * 事件产生类
 3  * Class EventGenerator
 4  */
 5 abstract class EventGenerator
 6 {
 7     private $ObServers = [];
 8 
 9     //增加观察者
10     public function add(ObServer $ObServer)
11     {
12         $this->ObServers[] = $ObServer;
13     }
14 
15     //事件通知
16     public function notify()
17     {
18         foreach ($this->ObServers as $ObServer) {
19             $ObServer->update();
20         }
21     }
22 
23 }
24 
25 /**
26  * 观察者接口类
27  * Interface ObServer
28  */
29 interface ObServer
30 {
31     public function update($event_info = null);
32 }
33 
34 /**
35  * 观察者1
36  */
37 class ObServer1 implements ObServer
38 {
39     public function update($event_info = null)
40     {
41         echo "观察者1 收到执行通知 执行完毕!
";
42     }
43 }
44 
45 /**
46  * 观察者2
47  */
48 class ObServer2 implements ObServer
49 {
50     public function update($event_info = null)
51     {
52         echo "观察者2 收到执行通知 执行完毕!
";
53     }
54 }
55 
56 /**
57  * 事件
58  * Class Event
59  */
60 class Event extends EventGenerator
61 {
62     /**
63      * 触发事件
64      */
65     public function trigger()
66     {
67         //通知观察者
68         $this->notify();
69     }
70 }
71 
72 //创建一个事件
73 $event = new Event();
74 //为事件增加旁观者
75 $event->add(new ObServer1());
76 $event->add(new ObServer2());
77 //执行事件 通知旁观者
78 $event->trigger();
原文地址:https://www.cnblogs.com/zuochuang/p/7250214.html