中介者模式:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
abstract class Country
{
protected $mediator;
public function __construct(UnitedNations $mediator)
{
$this->mediator = $mediator;
}
}
class USA extends Country
{
public function __construct(UnitedNations $mediator)
{
parent::__construct($mediator);
}
public function Declaration($message){
$this->mediator->Declaration($message,$this);
}
public function getMessage($message){
echo "美国获得对方信息:".$message."<br>";
}
}
class Iraq extends Country
{
public function __construct(UnitedNations $mediator)
{
parent::__construct($mediator);
}
public function Declaration($message){
$this->mediator->Declaration($message,$this);
}
public function getMessage($message){
echo "伊拉克获得对方信息".$message."<br>";
}
}
abstract class UnitedNations
{
public abstract function Declaration($message,Country $country);
}
class UnitedNationsSecurityCouncil extends UnitedNations
{
public $usa;
public $iraq;
public function Declaration($message,Country $country)
{
if($country == $this->usa){
$this->usa->getMessage($message);
}else{
$this->iraq->getMessage($message);
}
}
}
$unit = new UnitedNationsSecurityCouncil();
$c1 = new USA($unit);
$c2 = new Iraq($unit);
$unit->usa = $c1;
$unit->iraq = $c2;
$c1->Declaration("山姆大叔:伊拉克你有杀伤武器");
$c2->Declaration("萨达姆:我们没有杀伤武器");