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

yipeiwu_com6年前PHP代码库

观察者模式是设计模式中比较常见的一个模式,包含两个或者更多的互相交互的类。这一模式允许某个类观察另外一个类的状态,当被观察类的状态发生变化时候,观察者会进行得到通知进而更新相应状态。

php的SPL标准类库提供了SplSubject和SplObserver接口来实现,被观察的类叫subject,负责观察的类叫observer。这一模式是SplSubject类维护了一个特定状态,

当这个状态发生变化时候,它就会调用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 $image_file = $_GET['src']; $corn...

php下图片文字混合水印与缩略图实现代码

一 imageCreateFrom* 图片载入函数 //针对不同的后缀名图片 imagecreatefromgif imagecreatefromjpeg imagecreatefrom...

php smarty 二级分类代码和模版循环例子

php smarty 二级分类代码和模版循环例子

二级分类的数据表结构如下: PHP代码如下 复制代码 代码如下: /** @ 文章分类 含二级分类 @ param int $rootnum -- 一级分类数量 @ param int...

php5.3 废弃函数小结

在php5.3被放弃的函数有: ereg();//直接用mb_ereg代替,或是preg_match代替,但是匹配规则需要用/包括起来 eregi();//preg_match代替,在规...

控制PHP的输出:缓存并压缩动态页面

mod_gzip是一个Apache模块,其功能是使用Gzip压缩静态的html页面,遵循IETF标准的浏览器可以接受gzip编码(IE, Netscape等)。mod_gzip可以将页面...