例子说明

本篇例子来自Head First 里说的气象台例子,当气象台天气有变化时,订阅的气象站能及时更新

观察者

/**
 * 观察者接口
 * @author yaoran
 */
interface Observer
{
    public function update($temp, $dify, $pre);
}

被观察者
/**
 * 观察者模式-主题接口
 * @author yaoran
 */
interface Subject
{
    //注册观察者
    public function registerObserver(Observer $o);
    //移出观察者
    public function removeObserver(Observer $o);
    //通知观察者
    public function notifyObserver();
}

气象站

include 'Subject.php';
class WeatherData implements Subject
{
    //记录观察者数组
    private $observers;

    private $temp;

    private $dify;

    private $pre;

    public function __construct()
    {

    }

    public function registerObserver(Observer $o)
    {
        $this->observers[] = $o;
    }

    public function removeObserver(Observer $o)
    {
        if (in_array($o, $this->observers)) {
            $key = array_search($o, $this->observers);
            unset($this->observers[$key]);
        }
    }

    public function notifyObserver()
    {
        if (count($this->observers) > 0) {
            foreach ($this->observers as $k=>$o) {
                $o->update($this->temp, $this->dify, $this->pre);
            }
        }
    }


    //气象站有新数据后通知观察者
    public function meaChanged(){
        $this->notifyObserver();
    }


    public function setMea($temp, $dify, $pre) {
        $this->temp = $temp;
        $this->dify = $dify;
        $this->pre  = $pre;

        $this->notifyObserver();
    }
}

/**
 * 观察者显示接口
 */
interface Display
{
    public function display();
}

/**
 * 公告板 实现类
 * @author yaoran
 */
include 'Observer.php';
include 'Display.php';
class ConditDisplay implements Observer,Display
{

    private $temp;

    private $dify;

    private $pre;

    private $weaData;

    public function __construct(Subject $weaData)
    {
        $this->weaData = $weaData;
        $weaData->registerObserver($this);
    }

    public function update($temp, $dify, $pre)
    {
        $this->temp = $temp;
        $this->dify = $dify;
        $this->display();
    }

    public function display()
    {
        echo '当前公告板:' . $this->temp . '--' . $this->dify . "\r\n";
    }
}

yaoran
17 声望1 粉丝

喜欢代码,热爱生活,喜欢运动,平常爱看各种书籍,