当对象间存在一对多关系时,则使用观察者模式。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。
<?php interface Subject{ public function attach(Observer $observer); public function detach(Observer $observer); public function notify(); } class SubjectItem implements Subject{ private $observer_list; private $num; public function __construct(){ $this->observer_list = new SplObjectStorage; } public function attach(Observer $observer){ $this->observer_list->attach($observer); } public function detach(Observer $observer){ $this->observer_list->detach($observer); } public function setNum($num){ $this->num = $num; $this->notify(); } public function getNum(){ return $this->num; } public function notify(){ for($this->observer_list->rewind();$this->observer_list->valid();$this->observer_list->next()){ $this->observer_list->current()->update($this); } } } abstract class Observer{ abstract function update(Subject $subject); } class BinObserver extends Observer{ public function update(Subject $subject){ echo "二进制更新:".decbin($subject->getNum())." "; } } class OctObserver extends Observer{ public function update(Subject $subject){ echo "八进制更新:".decoct($subject->getNum())." "; } } class HexObserver extends Observer{ public function update(Subject $subject){ echo "十六进制更新:".dechex($subject->getNum())." "; } } $subject = new SubjectItem(); $subject->attach(new BinObserver()); $subject->attach(new OctObserver()); $subject->attach(new HexObserver()); $subject->setNum(22);
运行结果:
二进制更新:10110 八进制更新:26 十六进制更新:16