转载请注明作者和出处:https://www.jianshu.com/p/6678cf892a5d
运行平台: Windows
php版本: php7.0
作者简介: 一个本该成为游戏职业选手却被编程耽误的程序员
何为中介模式,就好像我们现在打电话,他有一个电话,我有一个电话,我们之间一条线就可以互相通电话,但是多了两个人,四个人,也就是说我们四个人需要6条电话线,随着人数的增多,这样的成本实在是太高了,于是我们就有了一个交换机(中介者),每次有新电话时候,只需要增加一条电话线去交换机便可,这就是中介者模式,增加一个中介者来过渡。
两个类之间不要相互调用,最好增加第三者类来进行调用,这样增加灵活性。
角色
- Mediator:抽象中介者角色,一般以抽象类的方式实现。
- ConcreteMediator:具体中介者角色,继承于抽象中介者,实现了父类定义的方法。
- Colleague:抽象同事类角色,定义了中介者对象的接口,它只知道中介者而不知道其他的同事对象。
//抽象电话类
abstract class Colleague{
protected $mediator;
abstract public function sendMsg($num,$msg);
abstract public function receiveMsg($msg);
//注册中介者
final public function setMediator(Mediator $mediator){
$this->mediator = $mediator;
}
}
//手机
class Phone extends Colleague{
public function sendMsg($num, $msg)
{
echo '打电话,嘟嘟嘟·····';
$this->mediator->opreation($num,$msg);
}
public function receiveMsg($msg)
{
echo "接电话,!!!!!!!!!!!".$msg;
}
}
//座机
class Telephone extends Colleague{
public function sendMsg($num, $msg)
{
echo '打电话,嘟嘟嘟·····';
$this->mediator->opreation($num,$msg);
}
public function receiveMsg($msg)
{
echo "彩铃,接电话,!!!!!!!!!!!".$msg;
}
}
//抽象类中介者
abstract class Mediator{
abstract public function opreation($id,$message);
abstract public function register($id,Colleague $colleague);
}
//交换级
class switches extends Mediator{
protected $colleagues = array();
public function opreation($id, $message)
{
if(!isset($this->colleagues[$id])){
echo "未注册手机号";
}
$this->colleagues[$id]->receiveMsg($id,$message);
}
public function register($id, Colleague $colleague)
{
if(!in_array($colleague,$this->colleagues)){
$this->colleagues[$id] = $colleague;
}
$colleague->setMediator($this);
}
}
$switches = new switches();//交换鸡
$telephone = new Telephone();//电话
$phone = new Phone();//手机
$switches->register(13537545111,$telephone);//注册手机号码
$switches->register(2144575,$phone);//注册电话号码号码
//通话
$phone->sendMsg(13537545111,'hello world');
$telephone->sendMsg(2144575,'请说普通话');
$telephone->sendMsg(2144575,'请说普通话');