以下是一个简单的 PHP 中介者模式的示例:
<?php
// 中介者接口
interface Mediator {
public function sendMessage($message, Colleague $colleague);
}
// 具体中介者类
class ConcreteMediator implements Mediator {
private $colleague1;
private $colleague2;
public function setColleague1(Colleague $colleague1) {
$this->colleague1 = $colleague1;
}
public function setColleague2(Colleague $colleague2) {
$this->colleague2 = $colleague2;
}
public function sendMessage($message, Colleague $colleague) {
if ($colleague == $this->colleague1) {
$this->colleague2->receiveMessage($message);
} elseif ($colleague == $this->colleague2) {
$this->colleague1->receiveMessage($message);
}
}
}
// 同事类
abstract class Colleague {
protected $mediator;
public function __construct(Mediator $mediator) {
$this->mediator = $mediator;
}
abstract public function send($message);
abstract public function receiveMessage($message);
}
// 具体同事类
class ConcreteColleague1 extends Colleague {
public function send($message) {
echo "Colleague1 sends message: $message\n";
$this->mediator->sendMessage($message, $this);
}
public function receiveMessage($message) {
echo "Colleague1 receives message: $message\n";
}
}
// 具体同事类
class ConcreteColleague2 extends Colleague {
public function send($message) {
echo "Colleague2 sends message: $message\n";
$this->mediator->sendMessage($message, $this);
}
public function receiveMessage($message) {
echo "Colleague2 receives message: $message\n";
}
}
// 客户端代码
$mediator = new ConcreteMediator();
$colleague1 = new ConcreteColleague1($mediator);
$colleague2 = new ConcreteColleague2($mediator);
$mediator->setColleague1($colleague1);
$mediator->setColleague2($colleague2);
$colleague1->send("Hello from Colleague1");
$colleague2->send("Hi from Colleague2");
在这个例子中,Mediator 接口定义了中介者的基本方法,包括 sendMessage。ConcreteMediator 类是具体中介者类,负责协调具体的同事对象之间的通信。
Colleague 是同事类的抽象基类,其中包含一个对中介者的引用。ConcreteColleague1 和 ConcreteColleague2 是具体的同事类,负责发送和接收消息。
客户端代码创建了中介者对象和两个具体同事对象,并将同事对象注册到中介者。当同事对象发送消息时,中介者负责转发消息给其他同事对象。
中介者模式有助于减少对象之间的直接依赖关系,提高系统的可维护性和灵活性。
转载请注明出处:http://www.pingtaimeng.com/article/detail/11956/PHP