<?php /** * 观察者模式 * 观察者抽象类 * 具体观察者类 * 被观察类抽象 * 具体观察类 * -------------------------- * 被观察者 保存 观察者的实例 * 当被观察者改动时,调用观察者实例调用 update 传入$this * 通知观察者数据更新 */ /** * Class ObeServer * 观察者 抽象类 */ abstract class AObeServer { abstract public function update(AComputer $AComputer); } /** * Class Object * 观察者 具体类 */ class ObeServer extends AObeServer { protected $objectName; function __construct($name) { $this->objectName = $name; } public function update(AComputer $AComputer) { // TODO: Implement update() method. $data = $AComputer->GetState(); echo '这里是观察者'.$this->objectName.'监听到变化'.$data.PHP_EOL; } } /** * Class AComputer * 被观察的目标抽象类 */ abstract class AComputer { // 存放观察者 protected static $_computer; // 自动构造初始化 public function __construct() { isset(self::$_computer) ? '' : self::$_computer = []; } // 添加一个观察者 public function Add(AObeServer $obeServer) { if (!in_array($obeServer, self::$_computer)) { self::$_computer[] = $obeServer; } } // 删除一个观察者 public function Remove(AObeServer $obeServer) { if (in_array($obeServer, self::$_computer)) { $key = self::$_computer[] = $obeServer; unset(self::$_computer[$key]); } } // 通知观察者 public function Notify() { foreach (self::$_computer as $key => $val) { $val->update($this); } } abstract public function SetState($state); abstract public function GetState(); } /** * Class DellComputer * 被观察对象实例 */ class DellComputer extends AComputer { protected $_dell; public function SetState($state) { // TODO: Implement SetState() method. $this->_dell = $state; } public function GetState() { // TODO: Implement GetState() method. return $this->_dell; } } // 建立观察者实例 $one_obe_server = new ObeServer('one'); $two_obe_server = new ObeServer('two'); // 建立被观察对象 $computer = new DellComputer(); // 被观察者注册添加观察者 $computer->Add($one_obe_server); $computer->Add($two_obe_server); // SetState改变状态,Notify通知 $computer->SetState(1); $computer->Notify(); // 输出 // 这里是观察者one监听到变化1 // 这里是观察者two监听到变化1