观察者模式,当一个对象状态发送改变时,依赖它的对象全部会收到通知,并自动更新。观察者模式实现了低耦合,非侵入式的通知与更新机制
*** index.php ***
define('BASEDIR',__DIR__);
include BASEDIR.'/Common/Loader.php';
spl_autoload_register('\\Common\\Loader::autoload');
use Server\EventGenerator;
use Server\Observer;
class Event extends EventGenerator{
function trigger() {
echo "start<br/>\n";
$this->notify();
}
}
class Observer1 implements Observer{
function update($event_info = null) {
echo "逻辑1<br />\n";
}
}
class Observer2 implements Observer{
function update($event_info = null) {
echo "逻辑2<br />\n";
}
}
$event = new Event;
$event->addObserver(new Observer1); //只需按接口新增观察者即可,不用修改原程序逻辑
$event->addObserver(new Observer2);
$event->trigger(); //start 逻辑1 逻辑2
*** EventGenerator.php ***
namespace Server;
abstract class EventGenerator {
private $observers = array();
//参数加定义,这里表示 必须是Observer接口的对象
function addObserver(Observer $observer) {
$this->observers[] = $observer;
}
function notify() {
foreach($this->observers as $observer) {
$observer->update();
}
}
}
*** Observer.php ***
namespace Server;
interface Observer{
function update($event_info = null);
}