SPL库-观察者模式

<?php
/**
 * @author :KangYunChuan
 * @name :观察者模式
 *
 */
class DemoSubject implements SplSubject {
    private 
$observers,$value;
    public function 
__construct(){
        
$this->observers = array();
    }
    public function 
attach(SplObserver $observer){
        
/**
         * 把SplObserver对象存入数组
         */
        
$this->observers[] = $observer;
    }
    public function 
detach(SplObserver $observer){
        if (
$idx array_search($observer,$this->observers,true)) {
            unset(
$this->observers[$idx]);
        }
    }
    public function 
notify(){
        
/**
         * 遍历SplObserver对象生成的数组
         */
            
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 blogger

博客-致力于分享PHP技术的开发心得, 记录站长生活的点点滴滴,PHP博客采用PHP 面向对象编程+Smarty模板引擎+Mysql数据库 开发(全站纯静态化与伪静态化)
QQ:334192009
电邮:admin@PHPdesigner.org

本站搜索

本站最新文章

博客最近档案

友情链接