Intermediary Mode
The intermediary mode is used to develop an object, which can transfer or mediate changes to the set of these objects if similar objects do not directly interact with each other. Generally, when processing non-coupling objects with similar properties that need to be synchronized, the best practice is the intermediary mode. PHP is not a commonly used design pattern.
Design scenario:
We have a CD class and an MP3 class. The structure of the two classes is similar.
We need to synchronously update the MP3 class when updating the CD class.
The traditional method is to instantiate the MP3 class in the CD class and then update it. But in this way, the code will be difficult to maintain. If the same MP4 class is added, so we can't deal with it.
The intermediary mode handles this situation well. Through the intermediary class, the data can be synchronously updated as long as the intermediary class is called in the CD class.
This design pattern has been used in our phpwind Forum before.
Code:
[Php]
<? Php
Class CD {
Public $ band = '';
Public $ title = '';
Protected $ _ mediator;
Public function _ construct (MusicContainerMediator $ mediator = NULL ){
$ This-> _ mediator = $ mediator;
}
Public function save (){
// Specific implementation to be determined
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
Class MP3Archive {
Protected $ _ mediator;
Public function _ construct (MusicContainerMediator $ mediator = NULL ){
$ This-> _ mediator = $ mediator;
}
Public function save (){
// Specific implementation to be determined
Var_dump ($ this );
}
Public function changeBandName ($ bandname ){
If (! Is_null ($ this-> _ mediator )){
$ This-> _ mediator-> change ($ this, array ("band" => $ bandname ));
}
$ This-> band = $ bandname;
$ This-> save ();
}
}
// Intermediary class
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 ();
}
}
}
}
// Test the instance
$ 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 ");
Author: initphp