欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-05-31 09:34:32
复制代码 代码如下:
复制代码 代码如下:

<?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");