本文实例讲述了php观察者模式原理与简单实现方法。分享给大家供大家参考,具体如下:
当一个对象状态发生改变后,会影响到其他几个对象的改变,这时候可以用观察者模式。像wordpress这样的应用程序中,它容外部开发组开发插件,比如用户授权的博客统计插件、积分插件,这时候可以应用观察者模式,先注册这些插件,当用户发布一篇博文后,就回自动通知相应的插件更新。
观察者模式符合接口隔离原则,实现了对象之间的松散耦合。
观察者模式uml图:
在php spl中已经提供splsubject和sqloberver接口
interface splsubject
{
function attach(splobserver $observer);
function detach(splobserver $observer);
function notify();
}
interface sqlobserver
{
function update(splsubject $subject);
}
下面具体实现上面例子
class 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
}
}
更多关于php相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《php基本语法入门教程》、《php数组(array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!