B8:中介者模式 Mediator

用一个中介对象来封装一系列的对象交互,中介者使得各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立的改变它们之间的交互.

减少了各对象之间的耦合,使得可以独立的改变或复用各个Mediator或Colleague
Mediator控制了交互,导致Mediator变的复杂

ps:

各个同事类需要知道中介者,但各个同事类并不知道彼此(各对象不需要显示的相互引用).

主要的交互逻辑由中介者完成

在同事类中添加接口来增加中介者,导致职责缺乏单一,除非是需要复杂的交互逻辑.

 

UML:

 

示例代码:

一个Colleague发消息,一个Colleague收消息,中介者处理交互.

// 抽象中介者
abstract class Mediator
{
    protected $sender;
    protected $receiver;

    public function setSender(Colleague $colleague)
    {
        $this->sender = $colleague;
    }

    public function setReceiver(Colleague $colleague)
    {
        $this->receiver = $colleague;
    }

    abstract public function sendMessage(Colleague $colleague, $message);
}

// 具体中介者
class ConcreateMediator extends Mediator
{
    public function sendMessage(Colleague $colleague, $message)
    {
        if ($colleague instanceof $this->sender) {
            $this->receiver->receiveMessage($message);
        }
    }
}

// 抽象同事
abstract class Colleague
{
    protected $mediator;

    public function __construct(Mediator $mediator)
    {
        $this->mediator = $mediator;
    }
}

// 同事1
class Colleague1 extends Colleague
{
    public function sendMessage($message)
    {
        $this->mediator->sendMessage($message, $this);
    }
}

// 同事2
class Colleague2 extends Colleague
{
    public function receiveMessage($message)
    {
        echo "同事2收到消息{$message}";
    }
}



$mediator = new ConcreateMediator();

$colleague1 = new Colleague1($mediator);
$colleague2 = new Colleague2($mediator);

$mediator->setSender($colleague1); // 命令一般由中介者发出
$mediator->setReceiver($colleague2);
$mediator->sendMessage($colleague1, '你好');

  

 

posted @ 2017-11-06 09:25  rorshach  阅读(163)  评论(0编辑  收藏  举报