ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 示例 **使用示例:** 使用 PHP 开发的程序中经常会使用外观模式。它在与复杂程序库和 API 协作时特别有用。 ## 概念示例 <details> <summary>main.php</summary> ``` <?php namespace RefactoringGuru\Facade\Conceptual; 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); ``` </details> <br /> 输出 ``` Facade initializes subsystems: Subsystem1: Ready! Subsystem2: Get ready! Facade orders subsystems to perform the action: Subsystem1: Go! Subsystem2: Fire! ``` ### 医院处方 <details> <summary>main.php</summary> ``` <?php //医院医生员工系统 class DoctorSystem{ //通知就诊医生 static public function getDoctor($name){ echo __CLASS__.":".$name."医生,挂你号".PHP_EOL; return new Doctor($name); } } //医生类 class Doctor{ public $name; public function __construct($name){ $this->name = $name; } public function prescribe($data){ echo __CLASS__.":"."开个处方给你".PHP_EOL; return "祖传秘方"; } } //患者系统 class SufferSystem{ static function getData($suffer){ $data = $suffer."资料"; echo __CLASS__.":".$suffer."的资料是这些".PHP_EOL; return $data; } } //医药系统 class MedicineSystem{ static function register($prescribe){ echo __CLASS__.":"."拿到处方:".$prescribe."------------通知药房发药了".PHP_EOL; Shop::setMedicine("砒霜5千克"); } } //药房 class shop{ static public $medicine; static function setMedicine($medicine){ self::$medicine = $medicine; } static function getMedicine(){ echo __CLASS__.":".self::$medicine.PHP_EOL; } } // 使用外观系统 // 挂号系统 class Facade{ static public function regist($suffer, $doct){ $doct = DoctorSystem::getDoctor($doct); //患者系统拿病历资料 $data = SufferSystem::getData($suffer); //医生看病历资料,开处方 $prscirbe = $doct->prescribe($data); //医药系统登记处方 MedicineSystem::register($prscirbe); //药房拿药 Shop::getMedicine(); } } //患者只需要挂一个号,其他的就让挂号系统去做吧。 Facade::regist("叶好龙", "贾中一"); ``` </details> <br /> 输出 ``` DoctorSystem:贾中一医生,挂你号 SufferSystem:叶好龙的资料是这些 Doctor:开个处方给你 MedicineSystem:拿到处方:祖传秘方------------通知药房发药了 shop:砒霜5千克 ```