GoF定义:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
这是消息传递中经常使用的一种模式,各个消息的发送者之间并不相互了解,但是它们之间是可以相互通讯的,就是通过一个消息转发中心来实现。
也好比邮件或者快递包裹的发送。
比如我需要邮寄一份邮件,我需要填写相关内容:接收者以及接收的内容,到邮局(注册)发送就可以了。
代码:
<?php
class SendStation{
protected $MemberList=[];
function SendInfo(Member $M,Information $Info){
//查看消息接收者中是否有注册的成员
foreach($this->MemberList as $K){
if($Info->GetSendType()==$K->GetReveiveType()){
if( !( $M==$K ) ){ //如果是自己就不接收消息了
$K->ReceiveMessage($Info); //接收消息
}
}
}
}
//注册成员
function register(Member $M){
$this->MemberList[$M->GetName()]=$M;
}
//反注册成员
function uninstall(Member $M){
unset( $this->MemberList[$M->GetName()] );
}
}
//定义消息类
class Information{
private $Sender;//发送者
private $SendType;//发送的消息类别
private $Content;//消息内容
function __construct($Sender,$SendType,$Content){
$this->Sender=$Sender;
$this->SendType=$SendType;
$this->Content=$Content;
}
function GetSendType(){
return $this->SendType;
}
function GetContent(){
return $this->Content;
}
function GetSender(){
return $this->Sender;
}
}
//定义成员类
abstract class Member{
private $Name;//名称
private $TS;//消息中转站
private $ReceiveType;//定义接收的消息种类
private $SendType;//定义发送的消息种类
function __construct(SendStation $T,string $Name,string $ReceiveType){
$this->TS=$T;
$this->Name=$Name;
$this->ReceiveType=$ReceiveType;
}
function SetReceiveInfoType($SIT){
$this->ReceiveInfoType=$SIT;
}
function GetName(){
return $this->Name;
}
function GetReveiveType(){
return $this->ReceiveType;
}
function SendInfo(Information $Info){
$this->TS->SendInfo($this,$Info);
}
abstract function ReceiveMessage(Information $I);
}
class MemberA extends Member {
function ReceiveMessage(Information $I){
echo $this->GetName()."接收到了消息:".$I->GetContent()."发送者:".$I->GetSender()."<br>";
}
}
class MemberB extends Member {
function ReceiveMessage(Information $I){
echo $this->GetName()."接收到了消息:".$I->GetContent()."发送者:".$I->GetSender()."<br>";
}
}
class MemberC extends Member {
function ReceiveMessage(Information $I){
echo $this->GetName()."接收到了消息:".$I->GetContent()."发送者:".$I->GetSender()."<br>";
}
}
class MemberD extends Member {
function ReceiveMessage(Information $I){
echo $this->GetName()."接收到了消息:".$I->GetContent()."发送者:".$I->GetSender()."<br>";
}
}
$SendStation=new SendStation;
$A=new MemberA($SendStation,"发送者A","天气预报");
$B=new MemberB($SendStation,"发送者B","新闻报道");
$C=new MemberC($SendStation,"发送者C","天气预报");
$D=new MemberD($SendStation,"发送者D","天气预报");
$SendStation->register($A);
$SendStation->register($B);
$SendStation->register($C);
$SendStation->register($D);
$I=new Information("发送者A","天气预报","这是发送者A发来的消息。");
$A->SendInfo($I);
echo "<br>";
$I=new Information("发送者C","新闻报道","这是发送者C发来的消息。");
$C->SendInfo($I);
?>
输出:
第一次发送:
发送者C接收到了消息:这是发送者A发来的消息。发送者:发送者A
发送者D接收到了消息:这是发送者A发来的消息。发送者:发送者A
第二次发送:
发送者B接收到了消息:这是发送者C发来的消息。发送者:发送者C
这个设计模式在稍微大一点的应用系统开发中很实用。