• 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();
    复制代码
     
     
     
  • 相关阅读:
    表达式计算
    atof和atoi
    十六进制与十进制之间的相互转换
    十六进制转八进制
    B. Blown Garland
    B. Arpa’s obvious problem and Mehrdad’s terrible solution
    ios::sync_with_stdio(false);
    1091 线段的重叠
    CODE[VS] 2614 安全区域
    CODE[VS] 2221 搬雕像 ——2011年台湾高级中学咨询学科能力竞赛
  • 原文地址:https://www.cnblogs.com/myJuly/p/10006393.html
Copyright © 2020-2023  润新知