<?php

//中介者设计模式用于开发一个对象,这个对象能够在类似对象相互之间不直接交互的情况下传送或调解对这些对象的集合的修改。

class CD{
    public $band = '';
    public $title = '';
    protected $_mediator;

    public function __construct($mediator = null){
        $this->_mediator = $mediator;
    }

    public function save(){
        var_dump($this);
    }

    public function changeBandName($newName){
        if(!is_null($this->_mediator)){
            $this->_mediator->change($this, ['band' => $newName]);
        }
        $this->band = $newName;
        $this->save();
    }
}

class MP3Archive{
    public $band = '';
    public $title = '';
    protected $_mediator;

    public function __construct($mediator = null){
        $this->_mediator = $mediator;
    }

    public function save(){
        var_dump($this);
    }

    public function changeBandName($newName){
        if(!is_null($this->_mediator)){
            $this->_mediator->change($this, ['band' => $newName]);
        }
        $this->band = $newName;
        $this->save();
    }
}

class MusicContainerMediator{
    protected $_containers = [];

    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(get_class($originalObject) != $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');

//处理具有类似属性并且属性需要保持同步的非耦合对象时,最佳的做法是使用基于中介者设计模式的对象。