當對象間存在一對多關係時,則使用觀察者模式。比如,當一個對象被修改時,則會自動通知它的依賴對象。觀察者模式屬於行為型模式。 運行結果: ...
當對象間存在一對多關係時,則使用觀察者模式。比如,當一個對象被修改時,則會自動通知它的依賴對象。觀察者模式屬於行為型模式。
<?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);
運行結果:
二進位更新:10110 八進位更新:26 十六進位更新:16