<?php /** * Created by PhpStorm. * User: Administrator * Date: 2016/6/27 * Time: 23:20 */ abstract class EventGenerator{ private $observers = array(); function addObserver(Observer $observer){ $this->observers[] = $observer; } function notify(){ foreach($this->observers as $observer){ $observer->update(); } } } interface Observer{ function update($event_info = NULL); } class Observer1 implements Observer{ function update($event_info = NULL) { // TODO: Implement update() method. echo '觀察者1<br>'; } } class Observer2 implements Observer{ function update($event_info = NULL) { // TODO: Implement update() method. echo "觀察者2<br>"; } } class Event extends EventGenerator{ function trigger(){ echo "Event<br>\n"; $this->notify(); ////邏輯1 //echo "邏輯1<br>"; ////邏輯3 //echo "邏輯2<br>"; ////邏輯3 //echo "邏輯3<br>"; } } $event = new Event(); $event->addObserver(new Observer1()); $event->addObserver(new Observer2()); $event->trigger();