當對象間存在一對多關係時,則使用觀察者模式。好比,當一個對象被修改時,則會自動通知它的依賴對象。觀察者模式屬於行爲型模式。php
<?php class Subject{ private $observer_list; private $num; public function __construct(){ $this->observer_list = new SplDoublyLinkedList(); } public function attach(Observer $observer){ $this->observer_list->push($observer); } public function setNum($num){ $this->num = $num; $this->notify(); } public function getNum(){ return $this->num; } public function notify(){ foreach ($this->observer_list as $observer) { $observer->update(); } } } abstract class Observer{ public $subj; public function __construct(Subject $subj){ $this->subj = $subj; $this->subj->attach($this); } abstract function update(); } class BinObserver extends Observer{ public function update(){ echo "二進制更新:".decbin($this->subj->getNum())."\n"; } } class OctObserver extends Observer{ public function update(){ echo "八進制更新:".decoct($this->subj->getNum())."\n"; } } class HexObserver extends Observer{ public function update(){ echo "十六進制更新:".dechex($this->subj->getNum())."\n"; } } $subject = new Subject(); new BinObserver($subject); new OctObserver($subject); new HexObserver($subject); $subject->setNum(22);
運行結果:this
二進制更新:10110 八進制更新:26 十六進制更新:16