例子:
<?php
/**
* 观察者模式(被观察者)
*
* @author Administrator
*
*/
class Subject implements SplSubject {
/**
* 设置的参数
*
* @var mixed
*/ by www.jb200.com
protected $_value;
/**
*
*
* @var SplObjectStorage
*/
protected $_observers;
/**
* 构造函数
*
* @return void
*/
public function __construct() {
$this->_observers = new SplObjectStorage();
}
/**
* (non-PHPdoc)
* @see SplSubject::attach()
*/
public function attach(SplObserver $observer) {
$this->_observers->attach($observer);
}
/**
* (non-PHPdoc)
* @see SplSubject::detach()
*/
public function detach(SplObserver $observer) {
$this->_observers->detach($observer);
}
/**
* (non-PHPdoc)
* @see SplSubject::notify()
*/
public function notify() {
foreach ($this->_observers as $observer) {
$observer->update($this);
}
}
/**
* 设置最新值
*
* @param mixed $value
* @return
*/
public function setValue($value) {
$this->_value = $value;
$this->notify();
}
/**
* 获取最后更新的值
*
* @return mixed
*/
public function getValue() {
return $this->_value;
}
}
/**
* 观察者模式(观察者)
*
* @author Administrator
*
*/
class Observer implements SplObserver {
/**
* (non-PHPdoc)
* @see SplObserver::update()
*/
public function update(SplSubject $subject) {
var_dump('最后更新时间为:' . $subject->getValue());
}
}
date_default_timezone_set('Asia/Shanghai');
error_reporting(E_ALL);
//调用示例