Heim  >  Artikel  >  Backend-Entwicklung  >  php中的观察者模式简单实例_PHP教程

php中的观察者模式简单实例_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:01:41834Durchsuche

php中的观察者模式简单实例

 这篇文章主要介绍了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);

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/971940.htmlTechArticlephp中的观察者模式简单实例 这篇文章主要介绍了php中的观察者模式简单实例,观察者模式是设计模式中比较常见的一个模式,包含两个或者更...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn