php設計模式 Observer(觀察者模式)

來源:互聯網
上載者:User

複製代碼 代碼如下:<?php
/**
* 觀察者模式
*
* 定義對象間的一種一對多的依賴關係,以便當一個對象的狀態發生改變時,所有依賴於它的對象都得到通知並自動重新整理
* 能夠便利地建立查看目標對象狀態的對象,並且提供與核心對象非耦合的指定功能
* 外掛程式系統
*/
class Observerable
{
private $_observers = array();

public function registerObserver($observer)
{
$this->_observers[] = $observer;
}

public function removeObserver($observer)
{
$key = array_search($observer,$this->_observers);
if(!($key === false))
{
unset($this->_observers[$key]);
}
}

public function notifyObservers()
{
foreach($this->_observers as $observer)
{
if($observer instanceof Observer) $observer->update($this);
}
}
}

interface Observer
{
public function update($observer);
}

interface DisplayElement
{
public function display();
}

// -- 執行個體類定義
class NewsObserverable extends Observerable
{
private $_sports_news;
public function setSportsNews($data)
{
$this->_sports_news = $data;
$this->notifyObservers();
}

public function getSportsNews()
{
return $this->_sports_news;
}

private $_local_news;
public function setLocalNews($data)
{
$this->_local_news = $data;
$this->notifyObservers();
}

public function getLocalNews()
{
return $this->_local_news;
}
}

class SportsNews implements Observer,DisplayElement
{
private $_data = null;
public function update($observer)
{
if($this->_data != $observer->getSportsNews())
{
$this->_data = $observer->getSportsNews();
$this->display();
}
}

public function display()
{
echo $this->_data.date("Y-m-d H:i:s")."<br/>";
}
}

class LocalNews implements Observer,DisplayElement
{
private $_data = null;
public function update($observer)
{
if($this->_data != $observer->getLocalNews())
{
$this->_data = $observer->getLocalNews();
$this->display();
}
}

public function display()
{
echo $this->_data.date("Y-m-d H:i:s")."<br/>";
}
}

// -- 執行個體化 ---

$objObserver = new NewsObserverable();
$local = new LocalNews();
$sports = new SportsNews();

$objObserver->registerObserver($local);
$objObserver->registerObserver($sports);

$objObserver->setSportsNews("sports news 1 ");
$objObserver->setLocalNews("local news 1 ");
$objObserver->removeObserver($sports);
$objObserver->setLocalNews("local news 2 ");
$objObserver->setSportsNews("sports news 2 ");
$objObserver->removeObserver($local);
$objObserver->setLocalNews("local news 3 ");

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.