时间:2021-07-01 10:21:17 帮助过:29人阅读
php的SPL标准类库提供了SplSubject和SplObserver接口来实现,被观察的类叫subject,负责观察的类叫observer。这一模式是SplSubject类维护了一个特定状态,
当这个状态发生变化时候,它就会调用notify方法。调用notify方法时,所有之前使用attach方法注册的SplObserver实例的update方法都会调用,Demo如下:
代码如下:
class DemoSubject 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 DemoObserver implements SplObserver{
public function update(SplSubject $subject){
echo 'The new value is '. $subject->getValue();
}
}
$subject = new DemoSubject();
$observer = new DemoObserver();
$subject->attach($observer);
$subject->setValue(5);