时间:2021-07-01 10:21:17 帮助过:15人阅读
观察者模式中有主题(即可观察者)和观察者。主题用一个共同的接口来通知观察者,主题不知道观察者的细节,只知道观察者实现了主题的接口。
普遍的观察者模式中的推的方式更适合点,下面我们就写一个推的例子,天气站提供一个接口,当天气变化时,会将数据通知给各个看板显示。
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;
}
}
?>
我们在这些对象之间用松耦合的方式进行沟通,这样我们在后期维护的时候,可以大大的提高效率。
设计原则:找出程序中会变化的方面,然后将其进行分离;针对接口编程,不针对实现编程;多用组合,少用继承
以上就介绍了Head First-观察者模式,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。