觀察者模式-例子1

例子說明

本篇例子來自Head First 裏說的氣象臺例子,當氣象臺天氣有變化時,訂閱的氣象站能及時更新php

觀察者

/**
 * 觀察者接口
 * @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";
    }
}
相關文章
相關標籤/搜索