PHP5+标准函数库观察者之实现
PHP的观察者设计模式实现相对简单,但是PHP5+版本中已经有标准库类库支持,我们只需简单继承并实现就可以了。
观察者:实现标准接口类库SplSubject。一个注册方法:attach,一个取消注册方法:detach。一个通知方法:nofity。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <?php
class TSPLSubject 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 ;
}
public function getValue(){
return $this ->value;
}
}
|
登入後複製
被观察者:实现标准接口类库SplObserver。一个update方法。
1 2 3 4 5 6 7 8 | <?php
class TSPLObserver implements SplObserver{
public function update(SplSubject $subject ){
echo 'The new state of subject ' , nl2br ( "\r\n" );
}
}
|
登入後複製
1 2 3 4 5 6 7 8 | <?php
class TSPLObserver1 implements SplObserver{
public function update(SplSubject $subject ){
echo 'The new state of subject one ' , nl2br ( "\r\n" );
}
}
|
登入後複製
测试调用(同目录下):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php
function __autoload( $classname ) {
require_once ( $classname . ".php" );
}
$subject = new TSPLSubject();
$subject ->attach( new TSPLObserver());
$observer1 = new TSPLObserver1();
$subject ->attach( $observer1 );
$subject ->notify();
exit ();
|
登入後複製
输出:
>php basic.php
The new state of subject
The new state of subject one
http://www.bkjia.com/PHPjc/875469.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/875469.htmlTechArticlePHP5+标准函数库观察者之实现 PHP的观察者设计模式实现相对简单,但是PHP5版本中已经有标准库类库支持,我们只需简单继承并实现就可以了...