觀察者模式
觀察者類
作用
<?php
//抽象主題
interface Subject{
public function attach($observer);
public function detach($observer);
public function notifyObservers();
}
//具體主題
class ConcreateSubject implements Subject{
private $_observers;
public function __construct(){
$this
}
public function attach($observer){
return array_push($this
}
public function detach($observer){
$index = array_search($observer
if($index === false || !array_key_exists($index
return false;
}
unset($this
return true;
}
public function notifyObservers(){
if(!is_array($this
return false;
}
foreach($this
$observer
}
return true;
}
}
//抽象觀察者
interface Observer{
public function update();
}
//具體觀察者
class ConcreteObserver implement Observer{
private $_name;
public function __construct($name){
$this
}
public function update(){
echo
}
}
//客戶端
class Client{
public static function main(){
$subject = new ConcreteSubject();
//新增第一個觀察者
$observer
$subject
//通知
$subject
//新增第二個觀察者
$observer
$subject
//通知
$subject
//刪除觀察者
$subject
//通知
$subject
}
}
Client::main();
?>
From:http://tw.wingwit.com/Article/program/PHP/201311/21261.html