目的
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设计模式之门面模式Facade的详细解析,更多关于该主题的资料请关注本站其他相关文章!