首页  >  文章  >  php教程  >  php设计模式 观察者模式,设计模式观察者

php设计模式 观察者模式,设计模式观察者

WBOY
WBOY原创
2016-06-13 08:45:19876浏览

php设计模式 观察者模式,设计模式观察者

观察者模式的核心是把客户元素(观察者)从一个中心类(主体)中分离开来。当主体知道事件发生时,观察者需要被通知到。同时,我们并不希望将主体与观察者之间的关系进行硬编码。为了达到这个目的,我们可以允许观察者在主体上进行注册。

观察者模式实现了低耦合、非侵入式的通知与更新机制。

场景:当一个事件发生后,要执行一连串更新操作。

<span>EventGenerator</span>.php
<?<span>php
namespace Baobab;
</span><span>/*</span><span>*
 * Class EventGenerator 基类,事件发生者
 </span><span>*/</span>
<span>abstract</span> <span>class</span><span> EventGenerator{

    </span><span>//</span><span>观察者对于事件发生者是不可见的,事件发生者不关心有哪些观察者关注了事件</span>
    <span>private</span> <span>$observers</span> = <span>array</span><span>();

    </span><span>/*</span><span>*
     * 添加观察者
     </span><span>*/</span>
    <span>function</span> addObserver(Observer <span>$observer</span><span>){
        </span><span>$this</span>->observers[] = <span>$observer</span><span>;
    }

    </span><span>/*</span><span>*
     *逐个通知观察者进行更新的操作
     </span><span>*/</span>
    <span>function</span><span> notify(){
        </span><span>foreach</span>(<span>$this</span>->observers <span>as</span> <span>$observer</span><span>){
            </span><span>$observer</span>-><span>update();
        }
    }
}</span>
<span>Observer</span>.php
<?<span>php
namespace Baobab;
</span><span>/*</span><span>*
 * Class Observer 观察者,观察的对象是事件发生者
 * @package Baobab
 </span><span>*/</span>
<span>interface</span><span> Observer{
    </span><span>/*</span><span>*
     * @param null $event_info  事件的信息
     * 表示事件发生后进行更新的操作
     </span><span>*/</span>
    <span>function</span> update(<span>$event_info</span> = <span>null</span><span>);
}</span>

index.php

<span>class</span> Event <span>extends</span><span> \Baobab\EventGenerator{
    </span><span>/*</span><span>*
     *触发一个新的事件
     </span><span>*/</span>
    <span>function</span><span> trigger(){
        </span><span>echo</span> 'Event发生'<span>;
        </span><span>$this</span>-><span>notify();
    }
}

</span><span>/*</span><span>*
 * 观察者1
 </span><span>*/</span>
<span>class</span> Observer1 <span>implements</span><span> \Baobab\Observer{
    </span><span>function</span> Update(<span>$event_info</span> = <span>null</span><span>){
        </span><span>echo</span> '更新操作代码1'<span>;
    }
}<br />
<span>/*<span>* <br /> * 观察者2 <br /><span> */</span></span></span>
</span><span>class</span> Observer2 <span>implements</span><span> \Baobab\Observer{
    </span><span>function</span> Update(<span>$event_info</span> = <span>null</span><span>){
        </span><span>echo</span> '更新操作代码2'<span>;
    }
}

</span><span>$event</span> = <span>new</span><span> Event();
</span><span>$event</span>->addObserver(<span>new</span><span> Observer1());
</span><span>$event</span>->addObserver(<span>new</span><span> Observer2());
</span><span>$event</span>->trigger();

 

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn