码迷,mamicode.com
首页 > 其他好文 > 详细

B8:中介者模式 Mediator

时间:2017-11-06 11:23:47      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:rac   public   creat   ima   idt   highlight   改变   send   str   

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

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

 

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, ‘你好‘);

  

 

B8:中介者模式 Mediator

标签:rac   public   creat   ima   idt   highlight   改变   send   str   

原文地址:http://www.cnblogs.com/itfenqing/p/7791669.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!