PHP设计模式-观察者

一个对象状态发生改变后,会影响到其他几个对象的改变,这时候可以用观察者模式。一个对象通过添加一个attach方法允许观察者注册自己,使本身变得可观察。当被观察的对象更改时,它会将消息发送到已注册的观察者。观察者使用该信息执行的操作与被观察的对象无关。观察者模式是一种事件系统,意味着这一模式允许某些类通过观察被观察类的状态变化,做出相应的动作。

观察者模式UML图

php5中提供了观察者observer与被观察者subject接口

interfaceSplSubject

{

functionattach(SplObserver$observer);

functiondetach(SplObserver$observer);

functionnotify();

}

interfaceSqlObserver

{

functionupdate(SplSubject$subject);

}

例子如下:

<?phpclassuserimplementsSplSubject{public$lognum;public$hobby;protected$observers;publicfunction__construct($hobby){$this->lognum=rand(1,10);$this->hobby=$hobby;$this->observers=newSplObjectStorage();}publicfunctionlogin(){$this->notify();}publicfunctionattach(SPLObserver$observer){$this->observers->attach($observer);}publicfunctiondetach(SPLObserver$observer){$this->observers->detach($observer);}publicfunctionnotify(){$this->observers->rewind();while($this->observers->valid){$observer=$this->observers->current();$observer->update($this);$this->observers->next();}}}classsecrityimplementsSPLObserver{publicfunctionupdate(SplSubject$subject){if($subject->lognum>=3){}else{}}}classadimplementsSPLObserver{publicfunctionupdate(SplSubject$subject){if($subject->hobby=="sports"){}else{}}}//实施观察$user=newuser("sports");$user->attach(newsecrity());$user->attach(newad());$user->login();?>