php中的观察者模式简单实例
观察者模式是设计模式中比较常见的一个模式,包含两个或者更多的互相交互的类。这一模式允许某个类观察另外一个类的状态,当被观察类的状态发生变化时候,观察者会进行得到通知进而更新相应状态。
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); 相关推荐
xzkjgw 2020-02-17
Stranger 2020-02-12
JF0 2020-01-12
luckymaoyy 2019-12-24
老杨叔叔 2016-02-03
Marsdanding 2019-06-30
dynsxyc 2019-06-30
guojing 2013-06-01
chengrile 2013-03-17
chaigang 2019-06-28
凌燕 2019-06-28
Android进阶 2019-06-27
dz00 2019-06-26
刘阳龙Herman 2019-06-14
xishizhaohua 2019-06-21
xhqiang 2019-06-21
trandy 2013-09-15