Intermediary Pattern
The Mediator pattern is used to develop an object that can communicate or mediate modifications to a collection of similar objects without directly communicating with each other. Generally, when dealing with uncoupled objects with similar properties that need to be kept synchronized, the best approach is the mediator pattern. A design pattern that is not particularly commonly used in PHP.
Design scene:
We have a CD class and an MP3 class, both classes have a similar structure.
We need to update the MP3 category simultaneously when the CD category is updated.
The traditional approach is to instantiate the MP3 class in the CD class and then update it. However, if you do this, the code will be difficult to maintain. If a new MP4 class is added, it will not be processed.
The mediator pattern handles this situation very well. Through the mediator class, as long as the mediator class is called in the CD class, the data can be updated synchronously.
In our phpwind forum, this design pattern has been used before.
Code:
[php]
class CD {
Public $band = '';
Public $title = '';
protected $_mediator;
Public function __construct(MusicContainerMediator $mediator = NULL) {
$this->_mediator = $mediator;
}
Public function save() {
//The specific implementation is to be determined
var_dump($this);
}
Public function changeBandName($bandname) {
If ( ! is_null($this->_mediator)) {
$this->band = $bandname;
$this->save();
}
//MP3Archive class
class MP3Archive {
protected $_mediator;
Public function __construct(MusicContainerMediator $mediator = NULL) {
$this->_mediator = $mediator;
Public function save() {
use use
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