中介者模式(Mediator Pattern)
中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。中介者模式属于行为型模式。
-
意图:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
-
主要解决:对象与对象之间存在大量的关联关系,这样势必会导致系统的结构变得很复杂,同时若一个对象发生改变,我们也需要跟踪与之相关联的对象,同时做出相应的处理。
-
何时使用:多个类相互耦合,形成了网状结构。
-
如何解决:将上述网状结构分离为星型结构。
-
关键代码:对象 Colleague 之间的通信封装到一个类中单独处理。
-
应用实例: 1、中国加入 WTO 之前是各个国家相互贸易,结构复杂,现在是各个国家通过 WTO 来互相贸易。 2、机场调度系统。 3、MVC 框架,其中C(控制器)就是 M(模型)和 V(视图)的中介者。
-
优点: 1、降低了类的复杂度,将一对多转化成了一对一。 2、各个类之间的解耦。 3、符合迪米特原则。
-
缺点:中介者会庞大,变得复杂难以维护。
-
使用场景: 1、系统中对象之间存在比较复杂的引用关系,导致它们之间的依赖关系结构混乱而且难以复用该对象。 2、想通过一个中间类来封装多个类中的行为,而又不想生成太多的子类。
-
注意事项:不应当在职责混乱的时候使用。
示例代码:
<?php
// Mediator 中介
class BaseStation
{
public function transmit($from, $to, $msg)
{
echo 'message received by BaseStation', PHP_EOL;
//基站转发信息到目标手机
echo 'message is forwarding from BaseStation', PHP_EOL;
$to->receiveMsg($from, $msg);
}
}
class Mobile
{
private $phoneNumber;
private $baseStation;
public function __construct($phoneNumber, $baseStation)
{
$this->phoneNumber=$phoneNumber;
$this->baseStation=$baseStation;
}
public function getPhoneNumber()
{
return $this->phoneNumber;
}
public function sendMsg($to, $msg)
{
//发送短信
echo $this->phoneNumber, ' send message to '.$to->getPhoneNumber(),':', $msg, PHP_EOL;
//基站接收处理
$this->baseStation->transmit($this, $to, $msg);
}
public function receiveMsg($from, $msg){
//收到短信
echo $this->phoneNumber, ' received message from ', $from->getPhoneNumber(),':', $msg, PHP_EOL;
}
}
function main()
{
$baseStation=new BaseStation;
$apple=new Mobile('134011****7', $baseStation);
$huawei=new Mobile('134011****2', $baseStation);
$apple->sendMsg($huawei, '你在干嘛呢?');
echo '----------------------------------------------------------------', PHP_EOL;
$huawei->sendMsg($apple, '为了挣大钱,好好学习!');
}main();
运行结果:
134011****7 send message to 134011****2:你在干嘛呢?
message received by BaseStation
message is forwarding from BaseStation
134011****2 received message from 134011****7:你在干嘛呢?
----------------------------------------------------------------
134011****2 send message to 134011****7:为了挣大钱,好好学习!
message received by BaseStation
message is forwarding from BaseStation
134011****7 received message from 134011****2:为了挣大钱,好好学习!