在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
当对象间存在一对多关系时,则使用观察者模式。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。 <?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())."\n"; } } class OctObserver extends Observer{ public function update(Subject $subject){ echo "八进制更新:".decoct($subject->getNum())."\n"; } } class HexObserver extends Observer{ public function update(Subject $subject){ echo "十六进制更新:".dechex($subject->getNum())."\n"; } } $subject = new SubjectItem(); $subject->attach(new BinObserver()); $subject->attach(new OctObserver()); $subject->attach(new HexObserver()); $subject->setNum(22);
运行结果: 二进制更新:10110 八进制更新:26 十六进制更新:16
|
2022-08-16
2022-11-06
2022-08-18
2022-08-15
2022-08-18
请发表评论