企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
#### 中介者模式 《设计模式:可复用面向对象软件的基础》一书中对中介者模式定义:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。 举个简单的例子,就比如大家平时喜欢用微信聊天,你发送的聊天内容需要通过微信服务器进行中间处理,然后下发给你的好友,微信服务器就是一个中介者。 `角色` Mediator: 抽象中介者 ConcreteMediator: 具体中介者 Colleague: 抽象同事类 ConcreteColleague: 具体同事类 `UML类图` ![此处输入图片的描述](https://doc.shiyanlou.com/document-uid108299labid2297timestamp1486375717275.png) `示例代码`:`Mediator.class.php` ~~~php <?php abstract class Colleague{ protected $mediator; abstract public function sendMsg($who,$msg); abstract public function receiveMsg($msg); public function setMediator(Mediator $mediator){ $this->mediator = $mediator; } } class ColleagueA extends Colleague { public function sendMsg($toWho,$msg) { echo "Send Msg From ColleagueA To: ".$toWho . '<br>'; $this->mediator->opreation($toWho,$msg); } public function receiveMsg($msg) { echo "ColleagueA Receive Msg: ".$msg . '<br>'; } } class ColleagueB extends Colleague { public function sendMsg($toWho,$msg) { echo "Send Msg From ColleagueB To: ".$toWho . '<br>'; $this->mediator->opreation($toWho,$msg); } public function receiveMsg($msg) { echo "ColleagueB Receive Msg: ".$msg . '<br>'; } } abstract class Mediator{ abstract public function opreation($id,$message); abstract public function register($id,Colleague $colleague); } class MyMediator extends Mediator { protected static $colleagues; function __construct() { if (!isset(self::$colleagues)) { self::$colleagues = []; } } public function opreation($id,$message) { if (!array_key_exists($id,self::$colleagues)) { echo "colleague not found"; return; } $colleague = self::$colleagues[$id]; $colleague->receiveMsg($message); } public function register($id,Colleague $colleague) { if (!in_array($colleague, self::$colleagues)) { self::$colleagues[$id] = $colleague; } $colleague->setMediator($this); } } $colleagueA = new ColleagueA(); $colleagueB = new ColleagueB(); $mediator = new MyMediator(); $mediator->register(1,$colleagueA); $mediator->register(2,$colleagueB); $colleagueA->sendMsg(2,'hello admin'); $colleagueB->sendMsg(1,'shiyanlou'); ~~~ 中介者模式的两个主要作用:中转作用(结构性):通过中介者提供的中转作用,各个同事对象就不再需要显式引用其他同事,当需要和其他同事进行通信时,通过中介者即可。该中转作用属于中介者在结构上的支持。 协调作用(行为性):中介者可以更进一步的对同事之间的关系进行封装,同事可以一致地和中介者进行交互,而不需要指明中介者需要具体怎么做,中介者根据封装在自身内部的协调逻辑,对同事的请求进行进一步处理,将同事成员之间的关系行为进行分离和封装。该协调作用属于中介者在行为上的支持。