The mediator pattern is used to develop an object that can transfer or mediate the modification of a collection of these objects in situations where similar objects are not directly connected to each other. when dealing with non-coupled objects that have similar properties and need to remain synchronized, the best practice is to broker mode. PHP is not a particularly common design pattern.
- We have a CD class and a MP3 class, and the structure of the two classes is similar.
- We need to update the MP3 class synchronously when the CD class is updated.
- The traditional approach is to instantiate the MP3 class in the CD class and then update it, but if you do, the code will be difficult to maintain, and if you add the same MP4 class, you won't be able to handle it.
- The mediator pattern is a good deal of this situation, through the Mediator class, the CD class, as long as the call to the intermediary class, you can update the data synchronously.
- This design pattern was previously useful in our Phpwind forum.
<?PHPclassCD { Public $band= ' '; Public $title= ' '; protected $_mediator; Public function__construct (Musiccontainermediator$mediator=NULL) { $this->_mediator =$mediator; } Public functionSave () {//Concrete implementation to be determined Var_dump($this); } Public functionChangebandname ($bandname) { if( !Is_null($this-_mediator)) { $this->_mediator->change ($this,Array("Band" =$bandname)); } $this->band =$bandname; $this-Save (); } } //Mp3archive class classmp3archive {protected $_mediator; Public function__construct (Musiccontainermediator$mediator=NULL) { $this->_mediator =$mediator; } Public functionSave () {//Concrete implementation to be determined Var_dump($this); } Public functionChangebandname ($bandname) { if( !Is_null($this-_mediator)) { $this->_mediator->change ($this,Array("Band" =$bandname)); } $this->band =$bandname; $this-Save (); } } //Intermediary class classMusiccontainermediator {protected $_containers=Array(); Public function__construct () {$this->_containers[] = "CD"; $this->_containers[] = "Mp3archive"; } Public functionChange$originalObject,$newValue) { $title=$originalObject-title; $band=$originalObject-Band; foreach($this->_containers as $container) { if( ! ($originalObjectinstanceof$container)) { $object=New $container; $object->title =$title; $object->band =$band; foreach($newValue as $key=$val) { $object-$key=$val; } $object-Save (); } } } } //Test Example $titleFromDB= "Waste of a Rib"; $bandFromDB= "Never Again"; $mediator=NewMusiccontainermediator (); $CD=NewCD ($mediator); $CD->title =$titleFromDB; $CD->band =$bandFromDB; $CD->changebandname ("Maybe Once more");
From: http://blog.csdn.net/initphp/article/details/7695805
PHP design mode series-Broker mode