目的
Facade通過嵌入多個(當然,有時只有一個)接口來解耦訪客與子系統,同時也為了降低復雜度。
- Facade 不會禁止你訪問子系統
- 你可以(應該)為一個子系統提供多個 Facade
因此一個好的 Facade 里面不會有 new 。如果每個方法里都要構造多個對象,那么它就不是 Facade,而是生成器或者[抽象|靜態|簡單] 工廠 [方法]。
優秀的 Facade 不會有 new,并且構造函數參數是接口類型的。如果你需要創建一個新實例,則在參數中傳入一個工廠對象。
UML
代碼
Facade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
<?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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php namespace DesignPatterns\Structural\Facade; /** * 創建操作系統接口類 OsInterface 。 */ interface OsInterface { /** * 聲明關機方法。 */ public function halt(); /** * 聲明獲取名稱方法,返回字符串格式數據。 */ public function getName(): string; } |
BiosInterface.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<?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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
<?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設計模式之門面模式Facade的詳細內容,更多關于PHP設計模式之門面模式Facade的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/phpyu/p/13681737.html