中介者: 中介者设计莫用于开发一个对象,这个对象能够在类似对象相互之间不直接交互的情况下传送或调节对这些对象的集合的修改
处理具有类似属性并且属性需要保持同步的非耦合对象时,最佳的做法是使用基于中介者设计模式的对象。
_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); ?>
数据库脚本请参照:http://www.cxybl.com/html/wlbc/php/2011_1126_9458.html