中介者模式

类图

2024072816363995.png

代码

<?php
 
// 中介者接口
interface Mediator
{
public function notify(string $event): void;
}
 
// 具体中介者类
class ConcreteMediator implements Mediator
{
private $component1;
private $component2;
 
public function setComponent1(Component1 $component1): void
{
$this->component1 = $component1;
$this->component1->setMediator($this);
}
 
public function setComponent2(Component2 $component2): void
{
$this->component2 = $component2;
$this->component2->setMediator($this);
}
 
public function notify(string $event): void
{
if ($event === "A") {
echo "中介者响应 A 事件,并触发以下操作:\n";
$this->component2->doC();
} elseif ($event === "B") {
echo "中介者响应 B 事件,并触发以下操作:\n";
$this->component1->doA();
}
}
}
 
// 基础组件类
class BaseComponent
{
protected $mediator;
 
public function setMediator(Mediator $mediator): void
{
$this->mediator = $mediator;
}
}
 
// 具体组件类 1
class Component1 extends BaseComponent
{
public function doA(): void
{
echo "组件 1 执行 A\n";
$this->mediator->notify("A");
}
 
public function doB(): void
{
echo "组件 1 执行 B\n";
$this->mediator->notify("B");
}
}
 
// 具体组件类 2
class Component2 extends BaseComponent
{
public function doC(): void
{
echo "组件 2 执行 C\n";
}
 
public function doD(): void
{
echo "组件 2 执行 D\n";
}
}
 
// 客户端代码
$component1 = new Component1();
$component2 = new Component2();
$mediator = new ConcreteMediator();
$mediator->setComponent1($component1);
$mediator->setComponent2($component2);
 
echo "客户端触发组件 1 的 A 操作:\n";
$component1->doA();
 
echo "\n客户端触发组件 1 的 B 操作:\n";
$component1->doB();