觀察者模式小示例
阿新 • • 發佈:2018-10-13
觀察 ade isset 消息 訂單狀態 ply 類名 htm clas header("Content-type:text/html;charset=utf-8");
/** public function release($type,$observer){
echo "發布成功";
$observer->runObserver($type,$this);
}
}
/**
- 類名:Observer
-
說明:觀察者模式
*/
class Observer{
// 聲明存放觀察者容器
protected $container = array();/*
- 新增觀察者函數
*/
public function addObserver($type, $observer) {
$this->container[$type][] = $observer;
}
/*
- 運行訂單觀察者
*/
public function runObserver($type,$obj) {
if (isset($this->container[$type])) {
$obj = new $obser();
$obj->update($obj);
}
}
}
}
- 新增觀察者函數
/**
- 類名:Order
- 說明:訂單類
-
觀察者模式的使用
*/
class Order {/*
- 創建訂單
*/
public function create($type,$observer) {
echo ‘購買成功<br/>‘;
$observer->runObserver($type,$this);
}
}
- 創建訂單
/*
- 類名:Email
- 說明:郵件類
*/
class Email {
public static function update($order) {
}
}
class Status {
public static function update($order) {
echo ‘改變訂單狀態<br/>‘;
}
}
$type1 = ‘buy‘;
$observer = new Observer();
$observer->addObServer($type1, ‘Email‘);
$observer->addObServer($type1, ‘Status‘);
$order = new Order();
$order->create($type1,$observer);
class Supply{
echo "發布成功";
$observer->runObserver($type,$this);
}
}
class Sms{
public static function update($supply){
echo "推送消息";
}
}
$type2 = ‘release‘;
$observer2 = new Observer();
$observer2->addObserver($type2,‘Sms‘);
$supply = new Supply();
$supply->release($type2,$observer2);
觀察者模式小示例