PHP设计模式之中介者模式浅析
作者:PHP隔壁老王邻居 时间:2023-05-25 04:07:16
中介者模式
中介者模式(Mediator Pattern)是一种常用的设计模式,用于解决各个对象之间的复杂依赖关系,使得各个对象之间可以独立地改变自己的行为,而不需要与其他对象发生直接的交互。中介者模式通过引入中介者对象来封装一系列的对象交互,中介者对象可以协调各个对象之间的行为,从而减少对象之间的耦合度。 中介者模式包含以下角色:
抽象中介者(Mediator):定义了各个对象之间的通信接口,可以是抽象类或接口。
具体中介者(ConcreteMediator):实现抽象中介者接口,负责协调各个对象之间的通信。
抽象同事类(Colleague):定义了各个对象之间的通信接口,可以是抽象类或接口。
具体同事类(ConcreteColleague):实现抽象同事类接口,维护与其他对象之间的通信关系。
PHP中的中介者模式
PHP中的中介者模式可以通过实现抽象中介者和抽象同事类来实现。下面是一个简单的示例:
<?php
// 抽象中介者
abstract class Mediator
{
abstract public function send($message, $colleague);
}
// 抽象同事类
abstract class Colleague
{
protected $mediator;
public function __construct(Mediator $mediator)
{
$this->mediator = $mediator;
}
abstract public function send($message);
abstract public function receive($message);
}
// 具体中介者
class ConcreteMediator extends Mediator
{
private $colleague1;
private $colleague2;
public function setColleague1(Colleague $colleague)
{
$this->colleague1 = $colleague;
}
public function setColleague2(Colleague $colleague)
{
$this->colleague2 = $colleague;
}
public function send($message, $colleague)
{
if ($colleague == $this->colleague1) {
$this->colleague2->receive($message);
} else {
$this->colleague1->receive($message);
}
}
}
// 具体同事类
class ConcreteColleague1 extends Colleague
{
public function send($message)
{
$this->mediator->send($message, $this);
}
public function receive($message)
{
echo "ConcreteColleague1 received message: $message\n";
}
}
class ConcreteColleague2 extends Colleague
{
public function send($message)
{
$this->mediator->send($message, $this);
}
public function receive($message)
{
echo "ConcreteColleague2 received message: $message\n";
}
}
以上代码中,我们定义了抽象中介者Mediator
和抽象同事类Colleague
,并分别实现了具体中介者ConcreteMediator
和具体同事类ConcreteColleague1
、ConcreteColleague2
。在具体中介者ConcreteMediator
中保存了两个具体同事类的引用,通过send()
方法来实现两个具体同事类之间的通信。具体同事类中实现了send()
和receive()
方法,通过中介者来发送和接收消息。 我们可以使用以下代码来测试中介者模式:
<?php
$mediator = new ConcreteMediator;
$colleague1 = new ConcreteColleague1($mediator);
$colleague2 = new ConcreteColleague2($mediator);
$mediator->setColleague1($colleague1);
$mediator->setColleague2($colleague2);
$colleague1->send("Hello, colleague2!");
$colleague2->send("Hi, colleague1!");
输出结果:
ConcreteColleague2 received message: Hello, colleague2!
ConcreteColleague1 received message: Hi, colleague1!
来源:https://blog.csdn.net/weixin_39934453/article/details/129725133