什么是观察者模式?观察者模式定义了对象之间一对多的关系。
观察者模式中有主题(即可观察者)和观察者。主题用一个共同的接口来通知观察者,主题不知道观察者的细节,只知道观察者实现了主题的接口。
普遍的观察者模式中的推的方式更适合点,下面我们就写一个推的例子,天气站提供一个接口,当天气变化时,会将数据通知给各个看板显示。
<?php//使用接口,类必须实现几个功能注册,删除,通知这几个动作interface Subject{public function registerObserver(Observer $o);public function removeObserver(Observer $o);public function notifyObservers();}interface Observer{public function update($a,$b,$c);}//各个面板不同将改行为以接口实现interface DisplayElement{public function display();}class Weather implements Subject{public $observers;public $changed=false;public $a;public $b;public $c;public function __construct(){$this->observers = array();}public function registerObserver(Observer $o){$this->observers[] = $o;}public function removeObserver(Observer $o){$key = array_search($o,$this->observers);if($key!==false){unset($this->observers[$key]);}}public function notifyObserver(){if($this->changed){foreach($this->observer as $ob){$ob->update($this->a,$this->b,$this->c);}}}public function setChanged(){$this->changed = true;}//当数值改变时通知各个观察者public function measurementsChanged(){$this->setChanged();$this->notifyObserver();}public function setMeasurements($a,$b,$c){$this->a = $a;$this->b = $b;$this->c = $c;$this->measurementsChanged();}}class CurrentConditionsDisplay implements Observer, DisplayElement{public $a;public $b;public $c;public $subject;public function __construct(Subject $weather){$this->subject = $weather;$this->subject->registerObserver($this);}public function update($a,$b,$c){$this->a = $a;$this->b = $b;$this->c = $c;$this->display();}public function display(){echo $this->a.$this->b.$this->c;}}?>
我们在这些对象之间用松耦合的方式进行沟通,这样我们在后期维护的时候,可以大大的提高效率。
设计原则:找出程序中会变化的方面,然后将其进行分离;针对接口编程,不针对实现编程;多用组合,少用继承