Home  >  Article  >  Backend Development  >  PHP设计模式--中介者模式

PHP设计模式--中介者模式

WBOY
WBOYOriginal
2016-06-23 13:33:05892browse

声明:本系列博客参考资料《大话设计模式》,作者程杰。

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


        UML类图:

        


          角色:       

          中介者接口(UnitedNations):在里面定义了各个同事之间相互交互所需要的方法。

          具体的中介者实现对象(UnitedCommit):它需要了解并为维护每个同事对象,并负责具体的协调各个同事对象的交互关系。

          同事类的定义(Country):通常实现成为抽象类,主要负责约束同事对象的类型,并实现一些具体同事类之间的公共功能,

          具体的同事类(China):实现自己的业务,需要与其他同事对象交互时,就通知中介对象,中介对象会负责后续的交互。


         核心代码:

         

<?php /** * Created by PhpStorm. * User: Jiang * Date: 2015/6/9 * Time: 21:15 *///中介者接口:可以是公共的方法,如Change方法,也可以是小范围的交互方法。//同事类定义:比如,每个具体同事类都应该知道中介者对象,也就是每个同事对象都会持有中介者对象的引用,这个功能可定义在这个类中。//抽象国家abstract class Country{    protected $mediator;    public function __construct(UnitedNations $_mediator)    {        $this->mediator = $_mediator;    }}//具体国家类//美国class USA extends Country{    function __construct(UnitedNations $mediator)    {        parent::__construct($mediator);    }    //声明    public function Declared($message)    {        $this->mediator->Declared($message,$this);    }    //获得消息    public function GetMessage($message)    {        echo "美国获得对方消息:$message<br>";    }}//中国class China extends Country{    public function __construct(UnitedNations $mediator)    {        parent::__construct($mediator);    }    //声明    public function  Declared($message)    {        $this->mediator->Declared($message, $this);    }    //获得消息    public function GetMessage($message)    {        echo "中方获得对方消息:$message<br>";    }}//抽象中介者//抽象联合国机构abstract class UnitedNations{    //声明    public abstract function Declared($message,Country $colleague);}//联合国机构class UnitedCommit extends UnitedNations{    public $countryUsa;    public $countryChina;    //声明    public function Declared($message, Country $colleague)    {        if($colleague==$this->countryChina)        {            $this->countryUsa->GetMessage($message);        }        else        {            $this->countryChina->GetMessage($message);        }    }}

          调用客户端测试代码:

         

header("Content-Type:text/html;charset=utf-8");//--------------------------中介者模式-------------------require_once "./Mediator/Mediator.php";//测试代码块$UNSC = new UnitedCommit();$c1 = new USA($UNSC);$c2 = new China($UNSC);$UNSC->countryChina = $c2;$UNSC->countryUsa =$c1;$c1->Declared("姚明的篮球打的就是好");$c2->Declared("谢谢。");

       适用场景:

       1、如果一组对象之间的通信方式比较复杂,导致相互依赖,结构混乱,可以采用中介者模式

       2、如果一个对象引用很多对象,并且跟这些对象交互,导致难以复用该对象


       欢迎关注我的视频课程,地址如下,谢谢。


   PHP面向对象设计模式
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn