中介者模式

<?php
/**
 * 加强版的门面模式
 * 将网状关系处理成中心点模式
 * 假设有这么一个需求:
 * 点击按钮提交表单,表单就填写一个名字
 * 列表页要增加一个名字
 * 统计栏要加1
 **/

//没引入中介者模式之前的 网状关系
class Button
{
    protected $count;
    protected $label;

    public function __construct()
    {
        $this->count = new Count();
        $this->label = new Label();
    }

    public function add($name)
    {
        echo '增加'.$name.'<br/>';

        $this->count->add($name);
        $this->label->add($name);
    }
}

class Count
{
    protected $num = 0;

    public function add()
    {
        //统计数量变动
        echo '数量++'.'<br/>';
        return ++$this->num;
    }
}

class Label
{
    protected $label_list = [];
    protected $map = [];

    public function add($name)
    {
        //列表增加人名
        echo '列表页增加'.$name.'<br/>';
        $this->map[$name] = count($this->label_list);
        $this->label_list[] = $name;
    }
}

//(new Button())->add('公子如玉');

class NewButton extends Button{
    protected $medium;

    public function __construct()
    {
        $this->medium = new Medium();
    }

    public function add($name){
        $this->medium->addUser($name);
    }
}

/**
 * Class Medium
 * 中介者模式优点:
 * 简化同事类之间的交互,由多对多交互变成一对多交互
 * 提同事类代码的复用性
 * 缺点:
 * 随着同事类的增加,中介者变得越来越复杂
 */
//引入中介者模式
class Medium{
   protected  $button;
   protected  $label;
   protected  $count;

   public function  __construct()
   {
       $this->button = new Button();
       $this->label = new Label();
       $this->count = new Count();
   }

   public function  addUser($name){
       echo '增加'.$name.'<br/>';
       $this->label->add($name);
       $this->count->add($name);
   }
}

(new NewButton())->add('世无双');

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值