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

中介者模式

时间:2018-07-02 00:14:44      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:this   模式   btn   str   int   get   his   private   标识   

<?php

abstract class Component
{
    protected $mediator;

    public function setMediator(Mediator $mediator){
        $this->mediator = $mediator;
    }
    
    public function getMediator(){
        return $this->mediator;
    }
    
    public function changed(){
        $this->mediator->componentChanged($this);
    }
    
    public abstract function update();
}

class Button extends Component
{
    private $id;
    
    public function getId(){
        return $this->id;
    }
    
    public function setId(int $id){
        $this->id = $id;
    }
    
    public function update(){
        echo ‘我被点击了‘;//这里只执行当前对象自身的事件
        $this->componentChanged();//交给中介者,让其执行其他对象的关联事件,例如:当前是添加学生按钮,添加以后,需要把刚刚添加的学生信息显示在表格的最上面一行
    }
}

class Table extends Component
{
    public function update($str = ‘‘){
        echo "<tr>{$str}</tr>";
    }
}

class Mediator
{
    private $addBtn;
    private $table;
    
    public function getTable(){
        return $this->table;
    }
    
    public function setTable(Table $table){
        $this->table = $table;
    }
    
    public function componentChanged(Component $component){
        if($component instanceof Button && 123 == $component->getId()){//假设id为1的按钮标识添加学生按钮
            $this->table->update(‘张三:男,年龄:18‘);
        }
    }
}

$addBtn = new Button();
$addBtn->setId(123);
$mediator = new Mediator();
$addBtn->setMediator($mediator);
$addBtn->update();

中介者模式

标签:this   模式   btn   str   int   get   his   private   标识   

原文地址:https://www.cnblogs.com/foolishnoob/p/9251802.html

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