PHP设计模式之中介者模式浅析(中介者模式的定义和特点)深度揭秘

随心笔谈2年前发布 编辑
171 0
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买

<?php
// 抽象中介者
abstract class Mediator
{
abstract public function send($message, $colleague);
}
// 抽象同事类
abstract class Colleague
{
protected $mediator;
public function __construct(Mediator $mediator)
{
$this->mediator=$mediator;
}
abstract public function send($message);
abstract public function receive($message);
}
// 具体中介者
class ConcreteMediator extends Mediator
{
private $colleague1;
private $colleague2;
public function setColleague1(Colleague $colleague)
{
$this->colleague1=$colleague;
}
public function setColleague2(Colleague $colleague)
{
$this->colleague2=$colleague;
}
public function send($message, $colleague)
{
if ($colleague==$this->colleague1) {
$this->colleague2->receive($message);
} else {
$this->colleague1->receive($message);
}
}
}
// 具体同事类
class ConcreteColleague1 extends Colleague
{
public function send($message)
{
$this->mediator->send($message, $this);
}
public function receive($message)
{
echo “ConcreteColleague1 received message: $message\n”;
}
}
class ConcreteColleague2 extends Colleague
{
public function send($message)
{
$this->mediator->send($message, $this);
}
public function receive($message)
{
echo “ConcreteColleague2 received message: $message\n”;
}
}

© 版权声明

相关文章