这两天看了下php的观察者模式,在此,总结下实现方法 先来解释下概念,观察者模式就是在对象之间定义一对多的依赖, 这样一来,当一个对象改变状态,依赖它的对象都会收到通知,并自动更新。 概念介绍到此,上代码 第一种方法: subject接口和observer接口都自己实现 <?php //主题接口 interface Subject{ public function registerObserver(Observer $o); //添加观察者 public function removeObserver(Observer $o); //移除观察者 public function notifyObservers(); //通知观察者 } //观察者接口 interface Observer{ function update($tmp, $hum, $pressure); } //主题类 class WetherData implements Subject{ private $observers = array(); private $tmp; //温度 private $hum; //湿度 private $pressure; //压力 function WetherData() { } function registerObserver(Observer $o) { $this->observers[] = $o; } function removeObserver(Observer $o) { if(is_array($this->observers) && count($this->observers) >= 1){ $key = array_search($o,$this->observers); unset($this->observers[$key]); } } function notifyObservers() { if(is_array($this->observers)){ foreach($this->observers as $k => $v){ $v->update($this->tmp, $this->hum, $this->pressure);//由主题进行‘推’传送,意思就是把所有的信息一次性传给观察者 //$v->update($this); 这种方式称为‘拉’,由观察者来决定自己需要获取的参数 } } } function setTmp($t) { $this->tmp = $t; } function getTmp() { return $this->tmp; } function setHum($h) { $this->hum = $h; } function getHum() { return $this->hum; } function setPressure($p) { $this->pressure = $p; } function getPressure() { return $this->pressure; } } //观察者A类 class A_observer implements Observer{ private $wetherData; function A_observer($wetherData) { $this->wetherData = $wetherData; $this->wetherData->registerObserver($this); } function update($tmp, $hum, $pressure) { //do something by yourself echo "温度:" . $tmp, "湿度:" . $hum, "压力:" .$pressure . "<br>"; } } $wetherData = new WetherData(); $A_observer = new A_observer($wetherData); $wetherData->setTmp('23.0'); $wetherData->setHum('25.0'); $wetherData->setPressure('250.0'); $wetherData->notifyObservers(); ?> 第二种方法,用php内置的观察者模式的接口 <?php /* 下面这个例子采用php内置的观察者模式 类SplSubject,SplObjectStorage,SplObserver均已内置 */ class Subject implements SplSubject { var $_value; var $_observers; function Subject() { $this->_observers = new SplObjectStorage(); } function attach(SplObserver $o) { $this->_observers->attach($o); } function detach(SplObserver $observer) { $this->_observers->detach($observer); } public function notify() { foreach ($this->_observers as $observer) { $observer->update($this); } } public function setValue($value) { $this->_value = $value; $this->notify(); } public function getValue() { return $this->_value; } } class Observer implements SplObserver { public function update(SplSubject $subject) { var_dump('值:' . $subject->getValue()); } } $Subject = new Subject(); $Observer = new Observer(); $Subject->attach($Observer); $Subject->setValue('1.2'); ?>