复制代码 代码如下:
<?php
//抽象主题
interface Subject{
public function attach($observer);
public function detach($observer);
public function notifyObservers();
}
//具体主题
class ConcreateSubject implements Subject{
private $_observers;
public function __construct(){
$this->_observers = array();
}
public function attach($observer){
return array_push($this->_observers,$observer);
}
public function detach($observer){
$index = array_search($observer,$this->_observers);
if($index === false || !array_key_exists($index,$this->_observers)){
return false;
}
unset($this->_observer[$index]);
return true;
}
public function notifyObservers(){
if(!is_array($this->_observers)){
return false;
}
foreach($this->_observers as $observer){
$observer->update();
}
return true;
}
}
//抽象观察者
interface Observer{
public function update();
}
//具体观察者
class ConcreteObserver implement Observer{
private $_name;
public function __construct($name){
$this->_name = $name;
}
public function update(){
echo 'Observer',$this->_name.'has notified<br/>';
}
}
//客户端
class Client{
public static function main(){
$subject = new ConcreteSubject();
//新增第一个观察者
$observer1 = new ConcreteObserver('Martin');
$subject->attach($observer1);
//通知
$subject->notifyObservers();
//新增第二个观察者
$observer2 = new ConcreteObserver('jaky');
$subject->attach($observer2);
//通知
$subject->notifyObservers();
//删除观察者1
$subject->deatch($observer1);
//通知
$subject->notifyObservers();
}
}
Client::main();
?>
新闻热点
疑难解答