Home > Backend Development > PHP Tutorial > PHP设计模式之观察者模式

PHP设计模式之观察者模式

WBOY
Release: 2016-06-23 13:16:53
Original
938 people have browsed it

<?phpnamespace Tools;    /*    观察者模式    当一个对象状态发生改变时,依赖它的对象全部会收到通知,并自动更新    观察者模式实现了低耦合,非侵入式的通知与更新机制    *///观察者接口interface Observer{    function update($event_info=null);}//事件发生者abstract class EventGenerator{    private $observers = array();//保存所有增加的观察者    //增加观察者    function addObserver(Observer $observer){        $this->observers[] = $observer;    }    //通知事件发生了,其他的观察者更新自己的逻辑    function notify(){        foreach($this->observers as $observer){            $observer->update();        }    }}//事件class Event extends EventGenerator{    function trigger(){        echo "Event<br>\n";        //事件发生后观察者执行的操作        $this->notify();    }}//观察者1class Observer1 implements \Tools\Observer{    function update($event_info=null){        echo "逻辑1<br>\n";    }}//观察者2class Observer2 implements \Tools\Observer{    function update($event_info=null){        echo "逻辑2<br>\n";    }}$event = new Event;$event->addObserver(new Observer1); //注入观察者1$event->addObserver(new Observer2); //注入观察者2$event->trigger();//触发事件
Copy after login



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template