<?php /** * 观察者就是定义各种功能的对象,(这些对象就是如果用户是猫的话,打印猫, * 用户如果是狗的话打印狗,用户如果是人的话打印人),被观察者对象要实现的就是 * 把添加(注册)的观察者对象储存起来并逐个通知执行观察者的功能 */ //观察者接口 interface Observer { public function update(); } //被观察者接口 interface Subject { public function addObserver(Observer $observer); public function notify(); } //被观察者继承类 class Action implements Subject { private $observer = array(); public function addObserver(Observer $observer) { // TODO: Implement addObserver() method. $this->$observer[] = $observer; } public function notify() { // TODO: Implement notify() method. foreach ($this->observer as $observer){ $observer->update(); } } } class cat implements Observer { public function update() { // TODO: Implement update() method. echo 'cat'; } } class dog implements Observer { public function update() { // TODO: Implement update() method. echo 'dog'; } } class people implements Observer { public function update() { // TODO: Implement update() method. echo 'people'; } } class pig implements Observer { public function update() { // TODO: Implement update() method. echo 'pig'; } } $action = new Action(); $action->addObserver(new cat()); $action->addObserver(new dog()); $action->addObserver(new people()); $action->addObserver(new pig()) $action->notify();