php设计模式 Mediator (中介者模式)

 2025-01-15  阅读 422  评论 8  点赞 386

摘要:复制代码 代码如下:
复制代码 代码如下:

<?php
/**
* 中介者模式
*
* 用一个中介对象来封装一系列的对象交互,使各对象不需要显式地相互引用从而使其耦合松散,而且可以独立地改变它们之间的交互
*/
abstract class mediator
{
abstract public function send($message,$colleague);
}
abstract class colleague
{
private $_mediator = null;
public function colleague($mediator)
{
$this->_mediator = $mediator;
}
public function send($message)
{
$this->_mediator->send($message,$this);
}
abstract public function notify($message);
}
class concretemediator extends mediator
{
private $_colleague1 = null;
private $_colleague2 = null;
public function send($message,$colleague)
{
if($colleague == $this->_colleague1)
{
$this->_colleague1->notify($message);
} else {
$this->_colleague2->notify($message);
}
}
public function set($colleague1,$colleague2)
{
$this->_colleague1 = $colleague1;
$this->_colleague2 = $colleague2;
}
}
class colleague1 extends colleague
{
public function notify($message)
{
echo "colleague1 message is :".$message."<br/>";
}
}
class colleague2 extends colleague
{
public function notify($message)
{
echo "colleague2 message is :".$message."<br/>";
}
}
//
$objmediator = new concretemediator();
$objc1 = new colleague1($objmediator);
$objc2 = new colleague2($objmediator);
$objmediator->set($objc1,$objc2);
$objc1->send("to c2 from c1");
$objc2->send("to c1 from c2");


标签:phpphp教程

评论列表:

  •   weihang
     发布于 2天前回复该评论
  • 写的很不错,学到了!
显示更多评论

发表评论:

管理员

承接各种程序开发,外贸网站代运营,外贸网站建设等项目
  • 内容2460
  • 积分67666
  • 金币86666

Copyright © 2024 LS'Blog-保定PHP程序员老宋个人博客 Inc. 保留所有权利。 Powered by LS'blog 3.0.3

页面耗时0.0272秒, 内存占用1.94 MB, 访问数据库29次

冀ICP备19034377号