外观模式

类图

2024072816340938.png

代码

<?php
 
// 子系统类 A
class SubsystemA
{
public function operationA1(): void
{
echo "SubsystemA: operationA1\n";
}
 
public function operationA2(): void
{
echo "SubsystemA: operationA2\n";
}
}
 
// 子系统类 B
class SubsystemB
{
public function operationB1(): void
{
echo "SubsystemB: operationB1\n";
}
 
public function operationB2(): void
{
echo "SubsystemB: operationB2\n";
}
}
 
// 子系统类 C
class SubsystemC
{
public function operationC1(): void
{
echo "SubsystemC: operationC1\n";
}
 
public function operationC2(): void
{
echo "SubsystemC: operationC2\n";
}
}
 
// 外观类
class Facade
{
protected $subsystemA;
protected $subsystemB;
protected $subsystemC;
 
public function __construct(SubsystemA $a, SubsystemB $b, SubsystemC $c)
{
$this->subsystemA = $a;
$this->subsystemB = $b;
$this->subsystemC = $c;
}
 
public function operation1(): void
{
echo "Facade: operation1\n";
$this->subsystemA->operationA1();
$this->subsystemB->operationB1();
}
 
public function operation2(): void
{
echo "Facade: operation2\n";
$this->subsystemA->operationA2();
$this->subsystemC->operationC1();
$this->subsystemB->operationB2();
}
}
 
// 客户端代码
$subsystemA = new SubsystemA();
$subsystemB = new SubsystemB();
$subsystemC = new SubsystemC();
 
$facade = new Facade($subsystemA, $subsystemB, $subsystemC);
 
echo "调用 Facade 的 operation1:\n";
$facade->operation1();
 
echo "\n调用 Facade 的 operation2:\n";
$facade->operation2();