当前位置: 移动技术网 > IT编程>软件设计>设计模式 > PHP设计模式—外观模式

PHP设计模式—外观模式

2020年05月05日  | 移动技术网IT编程  | 我要评论

 

定义:

外观模式(facade):又叫门面模式,为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

 

代码实例:

假设实现一个功能需要用到子系统中的四个方法。

/**
 * class subsystemone
 */
class subsystemone
{
    public function methodone()
    {
        return '子系统方法一' . '<br>';
    }
}

/**
 * class subsystemtwo
 */
class subsystemtwo
{
    public function methodtwo()
    {
        return '子系统方法二' . '<br>';
    }
}

/**
 * class subsystemthree
 */
class subsystemthree
{
    public function methodthree()
    {
        return '子系统方法三' . '<br>';
    }
}

/**
 * class subsystemfour
 */
class subsystemfour
{
    public function methodfour()
    {
        return '子系统方法四' . '<br>';
    }
}

如果不使用外观模式,客户端代码应该为:

$subsystemone = new subsystemone();
$subsystemtwo = new subsystemtwo();
$subsystemthree = new subsystemthree();
$subsystemfour = new subsystemfour();

echo $subsystemone->methodone();
echo $subsystemtwo->methodtwo();
echo $subsystemthree->methodthree();
echo $subsystemfour->methodfour();

这样的写法需要客户端了解子系统的具体实现方法,且代码没有解耦,如果子系统发生变化,则所有的客户端调用都需要进行相应的变化。

 

以下使用外观模式:
新增外观类facade.php

/**
 * 外观类,整合需要调用的子系统代码,给客户端调用,如果子系统发生变化,只用修改外观类代码
 * class facade
 */
class facade
{
    /**
     * @var
     */
    private $subsystemone;

    /**
     * @var
     */
    private $subsystemtwo;

    /**
     * @var
     */
    private $subsystemthree;

    /**
     * @var
     */
    private $subsystemfour;

    /**
     * facade constructor.
     */
    public function __construct()
    {
        $this->subsystemone = new subsystemone();
        $this->subsystemtwo = new subsystemtwo();
        $this->subsystemthree = new subsystemthree();
        $this->subsystemfour = new subsystemfour();
    }


    /**
     * 整合方法
     */
    public function method()
    {
        echo $this->subsystemone->methodone();
        echo $this->subsystemtwo->methodtwo();
        echo $this->subsystemthree->methodthree();
        echo $this->subsystemfour->methodfour();
    }
}

客户端调用:

$facade = new facade();
// 客户端可以不用知道子系统的存在,调用外观类中提供的方法就可以
$facade->method();

结果:

子系统方法一
子系统方法二
子系统方法三
子系统方法四

 

总结:

  • 外观模式能够为复杂系统提供简单且清晰的接口。
  • 外观模式只为系统中的某一层或子系统提供单一入口,能够帮助我们解耦项目中的不同部分,客户端只需调用一些简单方法,而不需要了解子系统的内部函数。
  • 当子系统发生变化时,只会对一个地方产生影响。
  • 如果希望客户端代码能简单地调用子系统或系统地改动不会影响客户端代码,那么就可以使用外观模式。

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网