目的
門面模式的最初目的並不是爲了避免讓你閱讀複雜的 API 文檔,這只是一個附帶作用。其實它的本意是爲了降低耦合性並且遵循 Demeter 定律。
Facade通過嵌入多個(當然,有時只有一個)接口來解耦訪客與子系統,同時也爲了降低複雜度。
Facade 不會禁止你訪問子系統
你可以(應該)爲一個子系統提供多個 Facade
因此一個好的 Facade 裏面不會有 new 。如果每個方法裏都要構造多個對象,那麼它就不是 Facade,而是生成器或者[抽象|靜態|簡單] 工廠 [方法]。
優秀的 Facade 不會有 new,並且構造函數參數是接口類型的。如果你需要創建一個新實例,則在參數中傳入一個工廠對象。
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)。
內容不錯的話希望大家支持鼓勵下點個贊/喜歡,歡迎一起來交流;另外如果有什麼問題 建議 想看的內容可以在評論提出