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

yipeiwu_com5年前PHP代码库
复制代码 代码如下:

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

相关文章

UCenter中的一个可逆加密函数authcode函数代码

复制代码 代码如下: function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) { $ckey_...

php中的单引号、双引号和转义字符详解

PHP单引号及双引号均可以修饰字符串类型的数据,如果修饰的字符串中含有变量(例$name);最大的区别是: 双引号会替换变量的值,而单引号会把它当做字符串输出。 例如: <&#...

PHP容易忘记的知识点分享

PHP容易忘记的知识点分享

1、定义常量: 复制代码 代码如下: <?php //1 define("TAX_RATE",0.08); echo TAX_RATE; //输出0.08 //2 (PHP 5.3...

解析php中heredoc的使用方法

Heredoc技术,在正规的PHP文档中和技术书籍中一般没有详细讲述,只是提到了这是一种Perl风格的字符串输出技术。但是现在的一些论坛程 序,和部分文章系统,都巧妙的使用heredoc...

PHP中文URL编解码(urlencode()rawurlencode()

下面是详细解释:///\\\ string urlencode ( string str) 返回字符串,此字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十...