-
目的
- 用一个对象来封装一系列的对象交互,中介者使各个对象不需要显示的相互引用,从而降低耦合,而且可以独立的改变他们之间的交互.
-
角色
1.抽象中介者(Mediator)定义了需要具体需要中介的对象到中介者的对象的接口
2.具体中介者(ConcreteMediator)实现抽象类的方法,他需要知道所有具体的中介的类,并从具体需要中介的 类接收,然后向具体需要中介的类发出命令
3.抽象需要中介的类(Colleague)
4.具体需要中介的类(ConcreateColleague)每个类都彼此不认识,他们有一个共同点都认识中介者对象 -
应用
QQ/微信等群聊;租房等中介平台;当多个对象需要进行通信时;当对象之间的通信可能发生变化时
-
代码1
<?php
/**
* 中介者模式
*/
//Mediator: 抽象中介者
abstract class Mediator
{
abstract public function Send($message,$colleague);
}
//Colleague: 抽象同事类
abstract class Colleague
{
public function __construct($mediator)
{
$this->mediator=$mediator;
}
}
//ConcreteMediator: 具体中介者
class ConcreteMediator extends Mediator
{
public function __set($name, $value)
{
$this->$name=$value;
}
public function Send($message, $colleague)
{
if ($colleague==$this->colleague1){
$this->colleague2->Notify($message);
}else{
$this->colleague1->Notify($message);
}
}
}
//ConcreteColleague: 具体同事类
class ConcreteColleague1 extends Colleague
{
public function Send($message){
$this->mediator->Send($message,$this);
}
public function Notify($message){
var_dump('1收到消息:'.$message);
}
}
class ConcreteColleague2 extends Colleague
{
public function Send($message){
$this->mediator->Send($message,$this);
}
public function Notify($message){
var_dump('2收到消息:'.$message);
}
}
$m=new ConcreteMediator();
$c1=new ConcreteColleague1($m);
$c2=new ConcreteColleague2($m);
$m->colleague1=$c1;
$m->colleague2=$c2;
$c1->Send('C1的消息');
$c2->Send('C2的消息');
结果
string '2收到消息:C1的消息' (length=27)
string '1收到消息:C2的消息' (length=27)
-
代码2
class CD{
protected $mid;
public function __construct($zj=null){
$this->mid = $zj;
}
public function change(){
if($this->mid){
$this->mid->comChange($this);
}
$this->save();
}
public function save(){
echo "this is CDclass ! <br /><br /><br />";
}
}
class MP3{
private $mid;
public function __construct($zj=null){
$this->mid = $zj;
}
public function change(){
if($this->mid){
<code class="php spaces"></code><code class="php variable">$this</code><code class="php plain">->mid->comChange(</code><code class="php variable">$this</code><code class="php plain">);</code>
}
$this->save();
}
public function save(){
echo "this is MP3class ! <br /><br /><br />";
}
}
//中间类
class ZhoneJie{
private $sonLists;
public function __construct(){
//等于是先注册,下一步的时候会排除一个,然后把剩余的都调用一遍
$this->sonLists [] = 'CD';
$this->sonLists [] = 'MP3';
}
public function comChange($baseObj,$parameter=array()){
//遍历初始化时候注册的 顾客
foreach($this->sonLists as $class){
//排除自身,然后剩余的其他顾客
if(!($baseObj instanceof $class)){
//把类名实例化成对象
$otherObj = new $class;
$otherObj->save($parameter);
}
}
}
}
//调用开始
$zj = new ZhoneJie; //new以后返回一个中介的对象,然后把这个对象传入到下面去,对象也可以当变量使用
$cd = new CD($zj);
$cd->change();