PHP觀察者模式

來源:互聯網
上載者:User

標籤:自動   logs   模式   情境   機制   依賴   code   維護   imp   

觀察者模式(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 ObServer28  */29 interface ObServer30 {31     public function update($event_info = null);32 }33 34 /**35  * 觀察者136  */37 class ObServer1 implements ObServer38 {39     public function update($event_info = null)40     {41         echo "觀察者1 收到執行通知 執行完畢!\n";42     }43 }44 45 /**46  * 觀察者247  */48 class ObServer2 implements ObServer49 {50     public function update($event_info = null)51     {52         echo "觀察者2 收到執行通知 執行完畢!\n";53     }54 }55 56 /**57  * 事件58  * Class Event59  */60 class Event extends EventGenerator61 {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();

 

PHP觀察者模式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.