當一個對象的狀態發生改變時,依賴他的對象會所有收到通知,並自動更新。php
一個事件發生後,要執行一連串更新操做。傳統的編程方式,就是在事件的代碼以後直接加入處理邏輯,當更新得邏輯增多以後,代碼會變得難以維護,這種方式是耦合的,侵入式的,增長新的邏輯須要改變事件主題的代碼。觀察者模式實現了低耦合,非侵入式的通知與更新機制。html
<?php abstract class EventGenerator { public $observers = []; public function addObservers(Observer $observer) { $this->observers[] = $observer; } public function notify($info = '') { foreach ($this->observers as $observer) { $observer->getInfo($info); } } } interface Observer { function getInfo($info = ''); } class Observer1 implements Observer { public function getInfo($info = '') { echo $info; } } class Events extends EventGenerator { private $info = 'init'; public function trigger($info = '') { echo "before:".$this->info."\r\n"; $this->info = $info; echo "after:".$this->info."\r\n"; $this->notify($info); } } $event = new Events(); $event->addObservers(new Observer1()); $event->trigger('hello world');