共计 1300 个字符,预计需要花费 4 分钟才能阅读完成。
简介
外观模式特点是屏蔽后端简单的实现逻辑,将其整合成简略的一个或几个接口提供进来,client 只需与 Facade 层提供的简略接口交互即可。
例如银行办业务,前面波及到很多财务细节,但用户面对的就是一个窗口业务员。
角色
- Facade 外观层
- Subsystem 负责具体事务的子系统们
类图
代码
class Facade
{
protected $subsystem1;
protected $subsystem2;
public function __construct(
Subsystem1 $subsystem1 = null,
Subsystem2 $subsystem2 = null
) {$this->subsystem1 = $subsystem1 ?: new Subsystem1();
$this->subsystem2 = $subsystem2 ?: new Subsystem2();}
public function operation(): string
{
$result = "Facade initializes subsystems:\n";
$result .= $this->subsystem1->operation1();
$result .= $this->subsystem2->operation1();
$result .= "Facade orders subsystems to perform the action:\n";
$result .= $this->subsystem1->operationN();
$result .= $this->subsystem2->operationZ();
return $result;
}
}
class Subsystem1
{public function operation1(): string
{return "Subsystem1: Ready!\n";}
public function operationN(): string
{return "Subsystem1: Go!\n";}
}
class Subsystem2
{public function operation1(): string
{return "Subsystem2: Get ready!\n";}
public function operationZ(): string
{return "Subsystem2: Fire!\n";}
}
function clientCode(Facade $facade)
{echo $facade->operation();
}
$subsystem1 = new Subsystem1();
$subsystem2 = new Subsystem2();
$facade = new Facade($subsystem1, $subsystem2);
clientCode($facade);
output:
Facade initializes subsystems:
Subsystem1: Ready!
Subsystem2: Get ready!
Facade orders subsystems to perform the action:
Subsystem1: Go!
Subsystem2: Fire!
本文由 mdnice 多平台公布
正文完