PHP设计模式系列(二十):中介者模式
来源:互联网 发布:淘宝培训学院 编辑:程序博客网 时间:2024/06/06 01:26
中介者模式
中介者模式(Mediator Pattern)定义:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。中介者模式又称为调停者模式,它是一种对象行为型模式。
模式结构
中介者模式包含如下角色:
- Mediator: 抽象中介者
- ConcreteMediator: 具体中介者
- Colleague: 抽象同事类
- ConcreteColleague: 具体同事类
结构图
PHP代码实现
<?php/** * 中介者模式 *///Mediator: 抽象中介者abstract class Mediator{ abstract public function Send($message,$colleague);}//Colleague: 抽象同事类abstract class Colleague{ public function __construct($mediator) { $this->mediator=$mediator; }}//ConcreteMediator: 具体中介者class ConcreteMediator extends Mediator{ public function __set($name, $value) { $this->$name=$value; } public function Send($message, $colleague) { if ($colleague==$this->colleague1){ $this->colleague2->Notify($message); }else{ $this->colleague1->Notify($message); } }}//ConcreteColleague: 具体同事类class ConcreteColleague1 extends Colleague{ public function Send($message){ $this->mediator->Send($message,$this); } public function Notify($message){ var_dump('1收到消息:'.$message); }}class ConcreteColleague2 extends Colleague{ public function Send($message){ $this->mediator->Send($message,$this); } public function Notify($message){ var_dump('2收到消息:'.$message); }}$m=new ConcreteMediator();$c1=new ConcreteColleague1($m);$c2=new ConcreteColleague2($m);$m->colleague1=$c1;$m->colleague2=$c2;$c1->Send('C1的消息');$c2->Send('C2的消息');
运行结果
string '2收到消息:C1的消息' (length=27)string '1收到消息:C2的消息' (length=27)
0 0
- PHP设计模式系列(二十):中介者模式
- PHP设计模式系列 - 中介者模式
- PHP设计模式系列 - 中介者模式
- Python设计模式(二十)【中介模式】
- JAVA系列-设计模式-中介者模式
- 设计模式系列:中介者模式
- Java/Android 设计模式系列(18)--中介者模式
- 大话设计模式二十五:中介者模式(mediator)
- 设计模式实现(二十一)---中介者模式(Mediator)
- JAVA--中介者模式(Mediator)--设计模式二十二
- 设计模式(二十一)中介者模式
- 设计模式—中介者模式(二十一)
- 设计模式(二十一)——中介者模式
- 大话设计模式-----(十)职责链模式、中介者模式
- 设计模式随笔(十):中介者(Mediator)
- PHP设计模式系列(十):抽象工厂模式
- java 开发模式之二十 :中介者模式
- 第二十一篇 设计模式--中介模式
- MySQL优化
- HRBUST 1855 幼稚园的矩阵(矩阵快速幂)
- 1020: 排序问题<2>
- CloudCompare插件编写二(数据结构)
- AJAX动态添加li之后无法触发事件
- PHP设计模式系列(二十):中介者模式
- 今日学习内容
- jq中的toggle和toggleClass
- RocketMQ源码解析:Message存储
- logistic回归
- java学习【知识点及代码10】
- HDU1698 Just a Hook(线段树+成段更新+lazy标记)
- 学习淘淘商城第四十六课(搜索服务Dao实现)
- 倒着打印单链表