php与设计模式-中介者模式

中介者模式

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

Demo


<?php 
   /**
    * Created by PhpStorm.
   //中介者接口:可以是公共的方法,如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); 
           } 
       } 
   } 

//测试代码块 
$UNSC = new UnitedCommit(); 
$c1 = new USA($UNSC); 
$c2 = new China($UNSC); 
$UNSC->countryChina = $c2; 
$UNSC->countryUsa =$c1; 
$c1->Declared("xx的篮球打的就是好"); 
$c2->Declared("谢谢。");

请关注我的订阅号

订阅号.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码哥说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值