用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式的相互引用,从而使其耦合松散,而且可以独立地改变他们的交互<br />这个就真的式中介了,你租房,他出租,中介在两边调节,<br />代理类只是返回一个类,用于代理控制,而不是交互<br />中介类处理两个交互类的关系,互相调用需要交互的对象的方法,而对象只需要调用中介提供的接口就可以<br />实现了用户之间的耦合,使得用户之间不用维护关系,都交给中介类,但是不适宜太多用户,不然,中介类会太过臃肿
<?php
//抽象中介类
abstract class Mediator
{
abstract public function Send($message, $colleague);
}
//中介实现类
class ConcreteMediator extends Mediator
{
//需要联系操作的类
public $colleague1;
public $colleague2;
//处理的方法,信息和当前的操作类
public function Send($message, $colleague)
{
if ($colleague == $this->colleague1) {
//执行对应类的处理方法
$this->colleague2->Notify($message);
} else {
$this->colleague1->Notify($message);
}
}
}
//联系抽象类
abstract class Colleague
{
protected $mediator;
protected $name;
public function __construct($mediator, $name)
{
$this->mediator = $mediator;
$this->name = $name;
}
}
//联系类A
class ConcreteColleagueA extends Colleague
{
//发送消息
public function Send(string $message)
{
$this->mediator->Send($this->name . "说:" . $message, $this);
}
//接受消息
public function Notify(string $message)
{
echo $this->name . "得到信息:" . $message, PHP_EOL;
}
}
//联系类B
class ConcreteColleagueB extends Colleague
{
public function Send(string $message)
{
$this->mediator->Send($this->name . "说:" . $message, $this);
}
public function Notify(string $message)
{
echo $this->name . "得到信息:" . $message, PHP_EOL;
}
}
//实例化中介类
$ConcreteMediator = new ConcreteMediator();
//联系类
$ConcreteColleagueA = new ConcreteColleagueA($ConcreteMediator, '天天');
$ConcreteColleagueB = new ConcreteColleagueB($ConcreteMediator, '小明');
//中介类对应关系
$ConcreteMediator->colleague1=$ConcreteColleagueA;
$ConcreteMediator->colleague2=$ConcreteColleagueB;
//联系
$ConcreteColleagueA->Send('你在哪呢,还不回来');
$ConcreteColleagueA->Send('再不回来,没肉吃了');
$ConcreteColleagueB->Send('等我,马上');