目的
门面模式的最初目的并非为了不让你阅读复杂的 API 文档,这只是一个附带做用。其实它的本意是为了下降耦合性而且遵循 Demeter 定律。php
Facade经过嵌入多个(固然,有时只有一个)接口来解耦访客与子系统,同时也为了下降复杂度。ios
Facade 不会禁止你访问子系统laravel
你能够(应该)为一个子系统提供多个 Facade面试
所以一个好的 Facade 里面不会有 new 。若是每一个方法里都要构造多个对象,那么它就不是 Facade,而是生成器或者[抽象|静态|简单] 工厂 [方法]。sql
优秀的 Facade 不会有 new,而且构造函数参数是接口类型的。若是你须要建立一个新实例,则在参数中传入一个工厂对象。shell
UML
代码
- Facade.php
<?php namespace DesignPatterns\Structural\Facade; class Facade { /** * @var OsInterface * 定义操做系统接口变量。 */ private $os; /** * @var BiosInterface * 定义基础输入输出系统接口变量。 */ private $bios; /** * @param BiosInterface $bios * @param OsInterface $os * 传入基础输入输出系统接口对象 $bios 。 * 传入操做系统接口对象 $os 。 */ public function __construct(BiosInterface $bios, OsInterface $os) { $this->bios = $bios; $this->os = $os; } /** * 构建基础输入输出系统执行启动方法。 */ public function turnOn() { $this->bios->execute(); $this->bios->waitForKeyPress(); $this->bios->launch($this->os); } /** * 构建系统关闭方法。 */ public function turnOff() { $this->os->halt(); $this->bios->powerDown(); } }
- OsInterface.php
<?php namespace DesignPatterns\Structural\Facade; /** * 建立操做系统接口类 OsInterface 。 */ interface OsInterface { /** * 声明关机方法。 */ public function halt(); /** * 声明获取名称方法,返回字符串格式数据。 */ public function getName(): string; }
- BiosInterface.php
<?php namespace DesignPatterns\Structural\Facade; /** * 建立基础输入输出系统接口类 BiosInterface 。 */ interface BiosInterface { /** * 声明执行方法。 */ public function execute(); /** * 声明等待密码输入方法 */ public function waitForKeyPress(); /** * 声明登陆方法。 */ public function launch(OsInterface $os); /** * 声明关机方法。 */ public function powerDown(); }
测试
- Tests/FacadeTest.php
<?php namespace DesignPatterns\Structural\Facade\Tests; use DesignPatterns\Structural\Facade\Facade; use DesignPatterns\Structural\Facade\OsInterface; use PHPUnit\Framework\TestCase; /** * 建立自动化测试单元 FacadeTest 。 */ class FacadeTest extends TestCase { public function testComputerOn() { /** @var OsInterface|\PHPUnit_Framework_MockObject_MockObject $os */ $os = $this->createMock('DesignPatterns\Structural\Facade\OsInterface'); $os->method('getName') ->will($this->returnValue('Linux')); $bios = $this->getMockBuilder('DesignPatterns\Structural\Facade\BiosInterface') ->setMethods(['launch', 'execute', 'waitForKeyPress']) ->disableAutoload() ->getMock(); $bios->expects($this->once()) ->method('launch') ->with($os); $facade = new Facade($bios, $os); // 门面接口很简单。 $facade->turnOn(); // 但你也能够访问底层组件。 $this->assertEquals('Linux', $os->getName()); } }
PHP 互联网架构师 50K 成长指南+行业问题解决总纲(持续更新)架构
面试10家公司,收获9个offer,2020年PHP 面试问题并发
★若是喜欢个人文章,想与更多资深开发者一块儿交流学习的话,获取更多大厂面试相关技术咨询和指导,欢迎加入咱们的群啊,暗号:phpzh(君羊号码856460874)。
内容不错的话但愿你们支持鼓励下点个赞/喜欢,欢迎一块儿来交流;另外若是有什么问题 建议 想看的内容能够在评论提出