【php设计模式】观察者模式
程序员文章站
2022-07-10 22:41:28
当对象间存在一对多关系时,则使用观察者模式。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。 运行结果: ......
当对象间存在一对多关系时,则使用观察者模式。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。
<?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