美文网首页
设计模式系列之---观察者模式

设计模式系列之---观察者模式

作者: 明天你好_ee9a | 来源:发表于2020-03-17 21:35 被阅读0次

观察者模式(Observer),当一个对象状态发生改变时,依赖它的对象全部会收到通知,并自动更新

<?php
//观察者模式
/**
* 观察者接口, 定义观察者具体需要执行的方法
* Interface Observer
*/
interface Observer
{
    /**
    * 广播通知后,所有已注册的观察者都需要执行该方法。
    * @return mixed
    */
    public function run();
}

/**
* 定义哈士奇类,实现具体细节
*/
class Hsq implements Observer{
    public function run(){
        echo 'hsq is fish <br/>';
    }
}

/**
 * 定义柯基类,实现具体细节
 */
class Kj implements Observer{
    public function run(){
        echo 'kj is run<br/>';
    }
}



/**
* 主题接口, 定义添加观察者和广播通知的方法
* Interface Notify
*/
interface Subject
{
    /**
    * 添加观察者
    * @param string $key 观察者对象指针
    * @param Observer $observer 观察者对象
    * @return mixed
    */
    public function addObserver($key, Observer $observer);

    /**
    * 从注册树中移除观察者
    * @param string $key 观察者对象指针
    * @return mixed
    */
    public function removeObserver($key);

    /**
    * 广播通知以注册的观察者
    * @return mixed
    */
    public function notify();
}

/**
* 主题具体实现
* Class Action
*/
class Action implements Subject
{
    /**
    * @var array 保存所有已注册的观察者
    */
    public $observer = [];

    /**
    * 添加观察者
    * @param string $key 观察者对象指针
    * @param Observer $observer 观察者对象
    * @return mixed
    */
    public function addObserver($key, Observer $observer){
        $this->observer[$key] = $observer;
    }

    /**
    * 移除观察者
    * @param string $key 观察者对象指针
    * @return mixed
    */
    public function removeObserver($key){
        unset($this->observer[$key]);
    }

    /**
    * 广播通知执行
    * @return mixed
    */
    public function notify(){
        foreach ($this->observer as $observer) {
            $observer->run();
        }
    }
}


//往注册数添加被观察的对象
$action = new Action();
//添加哈士奇进去
$action->addObserver('hsq',new Hsq());
//添加柯基进去
$action->addObserver('ke',new Kj());
//广播通知
$action->notify();

执行结果

image.png

相关文章

网友评论

      本文标题:设计模式系列之---观察者模式

      本文链接:https://www.haomeiwen.com/subject/iwchyhtx.html