当一个对象状态发生改变后,会影响到其他几个对象的改变,这时候可以用观察者模式。像wordpress这样的应用程序中,它容外部开发组开发插件,比如用户授权的博客统计插件、积分插件,这时候可以应用观察者模式,先注册这些插件,当用户发布一篇博文后,就回自动通知相应的插件更新。观察者模式符合接口隔离原则,实现了对象之间的松散耦合。观察者模式uml图:在php spl中已经提供splsubject和sqloberver接口[php] view plain copyinterface splsubject { function attach(splobserver $observer); function detach(splobserver $observer); function notify(); } interface sqlobserver { function update(splsubject $subject); } 下面具体实现上面例子[php] view plain copyclass subject implements splsubject { private $observers; public function attach(splobserver $observer) { if (!in_array($observer, $this->observers)) { $this->observers[] = $observer; } } public function detach(splobserver $observer) { if (false != ($index = array_search($observer, $this->observers))) { unset($this->observers[$index]); } } public function post() { //post相关code $this->notify(); } private function notify() { foreach ($this->observers as $observer) { $observer->update($this); } } public function setcount($count) { echo 数据量加 . $count; } public function setintegral($integral) { echo 积分量加 . $integral; } } class observer1 implements splobserver { public function update($subject) { $subject-> setcount(1); } } class observer2 implements splobserver { public function update($subject) { $subject-> setintegral(10); } } class client { public function test() { $subject = new subject(); $subject->attach(new observer1()); $subject->attach(new observer2()); $subject->post();//输出:数据量加1 积分量加10 } }