观察者模式是设计模式中比较常见的一个模式,包含两个或者更多的互相交互的类。这一模式允许某个类观察另外一个类的状态,当被观察类的状态发生变化时候,观察者会进行得到通知进而更新相应状态。
php的SPL标准类库提供了SplSubject和SplObserver接口来实现,被观察的类叫subject,负责观察的类叫observer。这一模式是SplSubject类维护了一个特定状态,
万通CMS网站管理系统采用PHP+MYSQL技术,支持伪静态功能,可生成google和百度地图,支持自定义url、关键字和描述,利于SEO搜索。拥有企业网站常用的模块功能(企业简介功能、新闻功能、产品功能、下载功能、图片功能、案例功能、在线留言、在线订单、友情链接、网站地图等等),功能强大,操作简单,灵活实用,是企业建站的神兵利器。我们的愿望是:让每个人都能用上 好用,实用,美观的网站,因为建站如
0
当这个状态发生变化时候,它就会调用notify方法。调用notify方法时,所有之前使用attach方法注册的SplObserver实例的update方法都会调用,Demo如下:
复制代码 代码如下:
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);
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号