其实观察者模式这是一种较为容易去理解的一种模式吧,它是一种事件系统,意味着这一模式允许某个类观察另一个类的状态,当被观察的类状态发生改变的时候,观察类可以收到通知并且做出相应的动作。比如键盘,我一敲击,系统就收到通知并进行相应的回应。
对于PHP来说,PHP内置提供了两个接口来供外部应用区实现这个模式。
SplSubject 接口,它代表着被观察的对象,其结构:
interface SplSubject{
public function attach(SplObserver $observer);
public function detach(SplObserver $observer);
public function notify();
}
SplObserver 接口,它代表着充当观察者的对象,其结构:
interface SplObserver{
public function update(SplSubject $subject);
}
这一个模式是这样实现的。SplSubject维护了一个特定的状态,当这个状态发生变化时,它就用notify()来通知之前用attach注册到SplSubject的所有SplObserver,并且调用其相应的update方法。
简单的例子:
class subject implements SplSubject{
private $observers , $value;
public function __construct(){
$this->observers = array();
}
public function attach(SplObserver $observer){
$this->observers[] = $observer;
}
public function detach(SplObserver $observer){
if($idx = array_search($observer, $this->observers, true)) {
unset($this->observers[$idx]);
}
}
public function notify(){
foreach($this->observers as $observer){
$observer->update($this);
}
}
public function setValue($value){
$this->value = $value;
$this->notify();
}
public function getValue(){
return $this->value;
}
}
class observer implements SplObserver{
public function update(SplSubject $subject){
echo ‘The new state of subject’.$subject->getValue();
}
}
$subject = new subject();
$observer = new observer();
$subject->attach($observer);
$subject->setValue(5);//observer会自动调用update方法,从而输出The new state of subject 5