场景:一个事件发生后,要执行一连串更新操作。传统的编程方式,就是在事件的代码之后直接加入处理逻辑。当更新的逻辑增加之后,代码会变得难以维护。这种方式是耦合的,侵入式的,增加新的逻辑需要修改事件主体的代码
$event = new Event(); $event->addObserver(new Observer1()); $event->addObserver(new Observer2()); $event->trigger();
class Event extends \IMooc\EventGenerator { function trigger() { echo "Event\n"; $this->notify(); } }
class Observer1 implements \IMooc\Observer { function update($event_info = null) { echo "逻辑1\n"; } } class Observer2 implements \IMooc\Observer { function update($event_info = null) { echo "逻辑2\n"; } }
observers[] = $observer; } function notify() { foreach ($this->observers as $observer) { $observer->update(); } } }