PHP设计模式--门面模式

172 阅读2分钟
<?php
/**
 * 门面模式
 */
class MessageInfo{
    public function send($service,$content){
        $service->send($content);
    }
}

class PushInfo{
    public function push($service,$content){
        $service->push($content);
    }
}

class BaiduyunService{
    public function send(string $content){
        echo '百度云发送短信:'.$content.',PHP_EOL';
    }

    public function push(string $content){
        echo '百度云发送通知:'.$content.',PHP_EOL';
    }
}

class AliyunService{
    public function send(string $content){
        echo '阿里云发送短信:'.$content.',PHP_EOL';
    }

    public function push(string $content){
        echo '阿里云发送通知:'.$content.',PHP_EOL';
    }
}

class Send{
    private $baiduyunService;
    private $aliyunService;

    private $messageInfo;
    private $pushInfo;

    public function __construct(){
        $this->baiduyunService = new BaiduyunService();
        $this->aliyunService = new AliyunService();

        $this->messageInfo = new MessageInfo();
        $this->pushInfo = new PushInfo();
    }

    public function sendAndPushBaidu($content){
        $this->messageInfo->send($this->baiduyunService,$content);
        $this->pushInfo->push($this->baiduyunService,$content);
    }

    public function sendAndPushAli($content){
        $this->messageInfo->send($this->aliyunService,$content);
        $this->pushInfo->push($this->aliyunService,$content);
    }
}

$send = new send();
$send->sendAndPushAli('下班');
$send->sendAndPushBaidu('下雨');

客户端的调用就非常简单了,我们不用知道具体调用了哪些子系统,只需要知道门面的这些方法干什么了就行啦!

  • 门面模式就是这么的简单,而且只要是真实的在项目中做过开发的朋友一定在不知不觉中就已经使用过这个模式了
  • 当你需要为一个复杂子系统提供一个简单的接口时,门面模式就非常适用。同时,如果客户程序与抽象类的实现部分之间存在着很大的依赖性时,也可以引入门面模式来进行解耦,提高子系统的独立性和可维护性。另外就是你需要构建一个层次结构的子系统时,门面可以充当每层子系统的入口点
  • Laravel中的门面系统相信使用过框架的人一定都用过,比如:Cache::put()。在Laravel中,门面的实现使用了一个魔术方法__callStatic()。然后让对象的方法可以实现直接使用静态方法来进行调用。是不是很神奇。有兴趣的朋友可以翻翻源码,就在/Illuminate/Support/Facades/Facade.php中。
  • 划重点:三层结构或者MVC也是门面模式的体现哦。上面说了,门面模式适合分层子系统的维护。而三层结构、MVC、MVP、MVVM这些货,本质上都是为了分层,而分层的目的,就是为了降低系统的复杂性。

来源:mp.weixin.qq.com/s?__biz=MzI…

感谢分享