子系统角色(Subsystem classes):实现子系统的功能,并处理由Facade对象指派的任务。对子系统而言,facade和client角色是未知的,没有Facade的任何相关信息;即没有指向Facade的实例。
客户角色(client):调用facade角色获得完成相应的功能。
7. 效果
Facade模式有下面一些优点:
1)对客户屏蔽子系统组件,减少了客户处理的对象数目并使得子系统使用起来更加容易。通过引入外观模式,客户代码将变得很简单,与之关联的对象也很少。
2)实现了子系统与客户之间的松耦合关系,这使得子系统的组件变化不会影响到调用它的客户类,只需要调整外观类即可。
3)降低了大型软件系统中的编译依赖性,并简化了系统在不同平台之间的移植过程,因为编译一个子系统一般不需要编译所有其他的子系统。一个子系统的修改对其他子系统没有任何影响,而且子系统内部变化也不会影响到外观对象。
4)只是提供了一个访问子系统的统一入口,并不影响用户直接使用子系统类。
Facade模式的缺点
1) 不能很好地限制客户使用子系统类,如果对客户访问子系统类做太多的限制则减少了可变性和灵活性。
2) 在不引入抽象外观类的情况下,增加新的子系统可能需要修改外观类或客户端的源代码,违背了“开闭原则”。
8. 实现
我们使用开关的例子;
<?php
/**
* 外观模式
*
*/
class SwitchFacade
{
private $_light = null; //电灯
private $_ac = null; //空调
private $_fan = null; //电扇
private $_tv = null; //电视
public function __construct()
{
$this->_light = new Light();
$this->_fan = new Fan();
$this->_ac = new AirConditioner();
$this->_tv = new Television();
}
/**
* 晚上开电灯
*
*/
public function method1($isOpen =1) {
if ($isOpen == 1) {
$this->_light->on();
$this->_fan->on();
$this->_ac->on();
$this->_tv->on();
}else{
$this->_light->off();
$this->_fan->off();
$this->_ac->off();
$this->_tv->off();
}
}
/**
* 白天不需要电灯
*
*/
public function method2() {
if ($isOpen == 1) {
$this->_fan->on();
$this->_ac->on();
$this->_tv->on();
}else{
$this->_fan->off();
$this->_ac->off();
$this->_tv->off();
}
}
}
/******************************************子系统类 ************/
/**
*
*/
class Light
{
private $_isOpen = 0;
public function on() {
echo 'Light is open', '<br/>';
$this->_isOpen = 1;
}
public function off() {
echo 'Light is off', '<br/>';
$this->_isOpen = 0;
}
}
class Fan
{
private $_isOpen = 0;
public function on() {
echo 'Fan is open', '<br/>';
$this->_isOpen = 1;
}
public function off() {
echo 'Fan is off', '<br/>';
$this->_isOpen = 0;
}
}
class AirConditioner
{
private $_isOpen = 0;
public function on() {
echo 'AirConditioner is open', '<br/>';
$this->_isOpen = 1;
}
public function off() {
echo 'AirConditioner is off', '<br/>';
$this->_isOpen = 0;
}
}
class Television
{
private $_isOpen = 0;
public function on() {
echo 'Television is open', '<br/>';
$this->_isOpen = 1;
}
public function off() {
echo 'Television is off', '<br/>';
$this->_isOpen = 0;
}
}
/**
* 客户类
*
*/
class client {
static function open() {
$f = new SwitchFacade();
$f->method1(1);
}
static function close() {
$f = new SwitchFacade();
$f->method1(0);
}
}
client::open();
内容版权声明:除非注明,否则皆为本站原创文章。
