源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

php中的观察者模式简单实例

  • 时间:2022-10-28 14:17 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:php中的观察者模式简单实例
观察者模式是设计模式中比较常见的一个模式,包含两个或者更多的互相交互的类。这一模式允许某个类观察另外一个类的状态,当被观察类的状态发生变化时候,观察者会进行得到通知进而更新相应状态。 php的SPL标准类库提供了SplSubject和SplObserver接口来实现,被观察的类叫subject,负责观察的类叫observer。这一模式是SplSubject类维护了一个特定状态, 当这个状态发生变化时候,它就会调用notify方法。调用notify方法时,所有之前使用attach方法注册的SplObserver实例的update方法都会调用,Demo如下:
[u]复制代码[/u] 代码如下:
class DemoSubject implements SplSubject{     private $observers, $value;       public function __construct(){         $this->observers = array();     }       public function attach(SplObserver $observer){         $this->observers[] = $observer;     }       public function detach(SplObserver $observer){         if($idx = array_search($observer, $this->observers, true)){             unset($this->observers[$idx]);         }     }       public function notify(){         foreach($this->observers as $observer){             $observer->update($this);         }     }       public function setValue($value){         $this->value = $value;         $this->notify();     }       public function getValue(){         return $this->value;     } }   class DemoObserver implements SplObserver{     public function update(SplSubject $subject){         echo 'The new value is '. $subject->getValue();     } }   $subject = new DemoSubject(); $observer = new DemoObserver(); $subject->attach($observer); $subject->setValue(5);
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部