什麼是觀察者模式?觀察者模式定義了對象之間一對多的關系。
觀察者模式中有主題(即可觀察者)和觀察者。主題用一個共同的接口來通知觀察者,主題不知道觀察者的細節,只知道觀察者實現了主題的接口。
普遍的觀察者模式中的推的方式更適合點,下面我們就寫一個推的例子,天氣站提供一個接口,當天氣變化時,會將數據通知給各個看板顯示。
<?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;
}
}
?>
我們在這些對象之間用松耦合的方式進行溝通,這樣我們在後期維護的時候,可以大大的提高效率。
設計原則:找出程序中會變化的方面,然後將其進行分離;針對接口編程,不針對實現編程;多用組合,少用繼承