Home  >  Article  >  php教程  >  PHP 观察者模式的实现代码

PHP 观察者模式的实现代码

WBOY
WBOYOriginal
2016-06-13 11:52:581009browse

代码如下所示:

复制代码 代码如下:


//被察者抽象类
class Observed implements SplSubject{
    protected $_name;
    protected $_observers;

    //实例化,生成一个观察者对象
    public function __construct(){
        $this->_observers = new SplObjectStorage();
    }

    // 添加观察者对象
    public function attach(SplObserver $observer){
        $this->_observers->attach($observer);
    }

    //删除观者对象
    public function detach(SplObserver $observer){
        $this->_observers->detach($observer);
    }

    //通知消息
    public function notify(){
        foreach($this->_observers as $observer){
            $observer->showMessage($this);
        }
    }

    //普通方法: 设置值
    public function setName($name){
        $this->_name = $name;
        $this->notify();
    }

    //普通方法: 获取值
    public function getName(){
        return $this->_name;
    }

    //普通方法:设置年龄
    public function setAge($age){
        $this->age = $age;
        foreach($this->_observers as $observer){
            $observer->showAge($this->_name,$this->age);
        }
    }

}

// 观察者抽象类
class Observer implements SplObserver{

    //显示消息提示
    public function showMessage(SplSubject $obj){
        $user = $obj->getName();
        if($user==='admin'){
            echo '您好, ',$user,'欢迎您进入管理后台
';
        }else{
            echo "你好, '$user' 你已经被添加到了用户列表
";
        }
    }
    //这是继承父类的抽象方法
    public function update(SplSubject $subject) {}

    //显示个人年龄
    public function showAge($name,$age){
        echo "<script>alert('$name 的年龄是: $age')</script>";
    }
}

$subject = new Observed();  //生成一个被观察者对象
$observer = new Observer(); //生成一个观察者对象
$subject->attach($observer);//把观察者传入到被观察中去
$subject->setName('张三'); //调用 setName 方法
/*
 * 通过面的 setName 就会调用  $this->notify();
* 通过调用  $this->notify()就会调用 $observer->showMessage($this)方法,
* 即每个观察者对象的 showMessage($obj)方法;
*/
$subject->setName('admin');
$subject->setAge(24);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn