中介者模式: 由一个中介对象来完成不同对象之间的交互;
例子(php): 一个经典的例子: 一个cd商城,底层有一个cd类和一个mp3类;当cd类的作者和名字有更新时,mp3也需要更新;使两个对象的数据统一;
class cd{
public $title;
public $author;
protected $mediator;
function __construct($mediator){
$this->mediator = $mediator;
}
function save(){
var_dump($this->title, $this->autor);
}
function change($title, $autor){
if($this->mediator){
$this->mediator->save($this, $title, $autor);
}
$this->save();
}
}
class Mp3{
public $title;
public $author;
protected $mediator;
function __construct($mediator){
$this->mediator = $mediator;
}
function save(){
var_dump($this->title, $this->autor);
}
function change($title, $autor){
if($this->mediator){
$this->mediator->save($this, $title, $author);
}
$this->save();
}
}
class meidator{
$containers = array();
function add($className){
$this->containers[] = $className;
}
function save($object, $title, $author){
foreach($this->containers as $class){
if(!($object instansof $class)){
$obj = new $class();
$obj->title = $title;
$obj->author = $author;
$this->save();
}
}
}
}
$mediator = new mediator();//中介者
$mediator->add('cd');//给中介添加需要处理的对象
$mediator->add('mp3'););//给中介添加需要处理的对象
$cd = new cd($mediator);
$cd->change('aaaaaaaa', 'author');//触发中介者处理mp3类