中介者模式
中介者模式用於開發一個對象,這個對象能夠在類似對象相互之間不直接相互的情況下傳送或者調解對這些對象的集合的修改。一般處理具有類似屬性,需要保持同步的非耦合對象時,最佳的做法就是中介者模式。PHP中不是特別常用的設計模式。
設計場景:
我們有一個CD類和一個MP3類,兩個類的結構相似。
我們需要在CD類更新的時候,同步更新MP3類。
傳統的做法就是在CD類中實例化MP3類,然後去更新,但是這麼做的話,代碼就會很難維護,如果新增一個同樣的MP4類,那麼就沒法處理了。
中介者模式很好的處理了這種情況,通過中介者類,CD類中只要調用中介者這個類,就能同步更新這些數據。
我們的phpwind論壇中,之前有用到過這個設計模式。
代碼:
[php]
<?php
class CD {
public $band = '';
public $title = '';
protected $_mediator;
public function __construct(MusicContainerMediator $mediator = NULL) {
$this->_mediator = $mediator;
}
public function save() {
//具體實現待定
var_dump($this);
}
public function changeBandName($bandname) {
if ( ! is_null($this->_mediator)) {
$this->_mediator->change($this, array("band" => $bandname));
}
$this->band = $bandname;
$this->save();
}
}
//MP3Archive類
class MP3Archive {
protected $_mediator;
public function __construct(MusicContainerMediator $mediator = NULL) {
$this->_mediator = $mediator;
}
public function save() {
//具體實現待定
var_dump($this);
}
public function changeBandName($bandname) {
if ( ! is_null($this->_mediator)) {
$this->_mediator->change($this, array("band" => $bandname));
}
$this->band = $bandname;
$this->save();
}
}
//中介者類
class MusicContainerMediator {
protected $_containers = array();
public function __construct() {
$this->_containers[] = "CD";
$this->_containers[] = "MP3Archive";
}
public function change($originalObject, $newValue) {
$title = $originalObject->title;
$band = $originalObject->band;
foreach ($this->_containers as $container) {
if ( ! ($originalObject instanceof $container)) {
$object = new $container;
$object->title = $title;
$object->band = $band;
foreach ($newValue as $key => $val) {
$object->$key = $val;
}
$object->save();
}
}
}
}
//測試實例
$titleFromDB = "Waste of a Rib";
$bandFromDB = "Never Again";
$mediator = new MusicContainerMediator();
$cd = new CD($mediator);
$cd->title = $titleFromDB;
$cd->band = $bandFromDB;
$cd->changeBandName("Maybe Once More");
作者:initphp