php 示例
最后更新于:2022-04-02 04:20:09
[TOC]
## 示例
**使用示例:** 使用 PHP 开发的程序中经常会使用外观模式。它在与复杂程序库和 API 协作时特别有用。
## 概念示例
输出 ``` Facade initializes subsystems: Subsystem1: Ready! Subsystem2: Get ready! Facade orders subsystems to perform the action: Subsystem1: Go! Subsystem2: Fire! ``` ### 医院处方
输出 ``` DoctorSystem:贾中一医生,挂你号 SufferSystem:叶好龙的资料是这些 Doctor:开个处方给你 MedicineSystem:拿到处方:祖传秘方------------通知药房发药了 shop:砒霜5千克 ```
';
main.php
``` 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); ```输出 ``` Facade initializes subsystems: Subsystem1: Ready! Subsystem2: Get ready! Facade orders subsystems to perform the action: Subsystem1: Go! Subsystem2: Fire! ``` ### 医院处方
main.php
``` 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("叶好龙", "贾中一"); ```输出 ``` DoctorSystem:贾中一医生,挂你号 SufferSystem:叶好龙的资料是这些 Doctor:开个处方给你 MedicineSystem:拿到处方:祖传秘方------------通知药房发药了 shop:砒霜5千克 ```