设计模式php实例:观察者模式
程序员文章站
2022-06-17 16:53:37
...
当一个对象状态发生改变后,会影响到其他几个对象的改变,这时候可以用观察者模式。像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 } }
上一篇: 微信营销平台系统–刮刮乐的开发