Head First-觀察者模式,headfirst-觀察者_PHP教程

來源:互聯網
上載者:User

Head First-觀察者模式,headfirst-觀察者


什麼是觀察者模式?觀察者模式定義了對象之間一對多的關係。

觀察者模式中有主題(即可觀察者)和觀察者。主題用一個共同的介面來通知觀察者,主題不知道觀察者的細節,只知道觀察者實現了主題的介面。

普遍的觀察者模式中的推的方式更適合點,下面我們就寫一個推的例子,天氣站提供一個介面,當天氣變化時,會將資料通知給各個看板顯示。

observers = array();}public function registerObserver(Observer $o){$this->observers[] = $o;}public function removeObserver(Observer $o){$key = array_search($o,$this->observers);if($key!==false){unset($this->observers[$key]);}}public function notifyObserver(){if($this->changed){foreach($this->observer as $ob){$ob->update($this->a,$this->b,$this->c);}}}public function setChanged(){$this->changed = true;}//當數值改變時通知各個觀察者public function measurementsChanged(){$this->setChanged();$this->notifyObserver();}public function setMeasurements($a,$b,$c){$this->a = $a;$this->b = $b;$this->c = $c;$this->measurementsChanged();}}class CurrentConditionsDisplay implements Observer, DisplayElement{public $a;public $b;public $c;public $subject;public function __construct(Subject $weather){$this->subject = $weather;$this->subject->registerObserver($this);}public function update($a,$b,$c){$this->a = $a;$this->b = $b;$this->c = $c;$this->display();}public function display(){echo $this->a.$this->b.$this->c;}}?>

我們在這些對象之間用松耦合的方式進行溝通,這樣我們在後期維護的時候,可以大大的提高效率。

設計原則:找出程式中會變化的方面,然後將其進行分離;針對介面編程,不針對實現編程;多用組合,少用繼承

http://www.bkjia.com/PHPjc/946585.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/946585.htmlTechArticleHead First-觀察者模式,headfirst-觀察者 什麼是觀察者模式?觀察者模式定義了對象之間一對多的關係。 觀察者模式中有主題(即可觀察者)...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.