php 觀察者模式

來源:互聯網
上載者:User
先不說定義,先來看運用情境,這些定義咋的,老懞,由情境想到設計模式顯然是比較好理解的一個方法。

情境:新使用者名稱註冊完 要完成的工作:1,新使用者送積分 2,新使用者送優惠? 3,記錄新使用者log日誌

觀察者模式:

  通過情境我們可以分析,當使用者註冊完,系統要執行一系列商務邏輯,我們可以把這一系列商務邏輯看成觀察者,分別有積分類觀察者,優惠?類觀察者,log類觀察者,

這些觀察者一直在監聽使用者類,當使用者執行註冊這個動作之後,觀察者們各自開始自己的商務邏輯。

分析:整個運用情境可以有兩個類完成,一個是觀察者類,另一個是被觀察類(主題),他們有各自的介面,觀察者類介面是接收到被觀察者的通知之後,更新狀態,被觀察者介面是

//主題類介面(被觀察者)
interface SubjectInterface{
public function addObserver();
}
//觀察者介面
interface ObserverInterface{
public function beginActionAfterNotifity();
}

//主題類
class Subject implements SubjectInterface{
private $_oberver=array();
//添加觀察者
public function addObserver($oberver){
$this->_oberver[]=$oberver;
}
//通知
public function notifity(){
foreach ($this->_oberver as $oberver){
$oberver->beginActionAfterNotifity();
}
}

}
//積分類
class Point implements ObserverInterface{
public function beginActionAfterNotifity(){
echo "送積分啦";
}
}
//優惠?類
class Coupon implements ObserverInterface{
public function beginActionAfterNotifity(){
echo "送優惠?啦";
}
}
//日誌類
class Log implements ObserverInterface{
public function beginActionAfterNotifity(){
echo "你被記錄了";
}
}


//動作類
class User {
function addUser(){
//添加新使用者之後
$this->addObserver();
}
function addObserver(){
$subject=new Subject();
$subject->addObserver(new Point());
$subject->addObserver(new Coupon());
$subject->addObserver(new Log());
}
}

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.