美文网首页设计模式
设计模式 外观模式

设计模式 外观模式

作者: Yohann丶blog | 来源:发表于2020-06-10 17:54 被阅读0次
    WechatIMG34.jpeg

    介绍

    shiyankou:外观模式(Facade Pattern):外部与一个子系统的通信必须通过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。外观模式又称为门面模式,它是一种对象结构型模式。使用外观模式最大的优点就是子系统与客户端之间是松耦合的关系,客户端不必知道具体有哪些子系统,也无需知道他们是如何工作的,通过引入一个外观类,提供一个客户端间接访问子系统的高级接口。子系统和外观类可以独立运作,修改某一个子系统的内容,不会影响到其他子系统,也不会影响到外观对象。不过它的缺点就是它不够灵活,当需要增加一个子系统的时候,需要修改外观类。

    角色

    角色 说明
    Client 客户角色
    Facade 外观角色,提供高级接口
    SubSystem 子系统角色,负责各自的功能实现

    角色示例

    类名 担任角色 说明
    Phone Client 手机
    Reboot Facade 重启
    Shutdown SubSystem 关机
    Boot SubSystem 开机

    UML类图

    外观模式.jpg

    代码

    <?php 
    class Shutdown
    {
        public function execute()
        {
            return "关机".PHP_EOL;
        }
    }
    
    class Boot
    {
        public function execute()
        {
            return "开机".PHP_EOL;
        }
    }
    
    class Reboot
    {
        protected $shutdown;
        protected $boot;
    
        function __construct()
        {
            $this->shutdown = new Shutdown();
            $this->boot = new Boot();
        }
    
        public function execute()
        {
            return $this->shutdown->execute().$this->boot->execute();
        }
    }
    
    class Phone
    {
        public $reboot;
    
        function __construct()
        {
            $this->reboot = new Reboot();
        }
    }
    
    $phone = new Phone();
    echo $phone->reboot->execute();
    

    创建 Reboot.php,内容如上。

    执行

    $ php Reboot.php
    关机
    开机
    

    相关文章

      网友评论

        本文标题:设计模式 外观模式

        本文链接:https://www.haomeiwen.com/subject/kpiptktx.html