PHP设计模式系列(七):外观模式

这篇博客探讨了PHP中的外观模式,旨在简化子系统的交互。内容包括模式的结构解释,角色定义如外观角色和子系统角色,并提供了具体的PHP代码实现及运行结果展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

外观模式

外观模式(Facade Pattern):外部与一个子系统的通信必须通过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。外观模式又称为门面模式,它是一种对象结构型模式。

模式结构

外观模式包含如下角色:

  • Facade: 外观角色
  • SubSystem:子系统角色

结构图

这里写图片描述

PHP代码实现

<?php
/**
 * 外观模式
 */
//SubSystem:子系统角色
class SubSystemOne
{
    public function MethodOne(){
        var_dump('子系统方法一');
    }
}
class SubSystemTwo
{
    public function MethodTwo(){
        var_dump('子系统方法二');
    }
}
class SubSystemThree
{
    public function MethodThree(){
        var_dump('子系统方法三');
    }
}
class SubSystemFour
{
    public function MethodFour(){
        var_dump('子系统方法四');
    }
}

//Facade: 外观角色
class Facade
{
    public function __construct(){
        $this->one=new SubSystemOne();
        $this->two=new SubSystemTwo();
        $this->three=new SubSystemThree();
        $this->four=new SubSystemFour();
    }
    public function MethodA(){
        var_dump('方法组A');
        $this->one->MethodOne();
        $this->two->MethodTwo();
    }
    public function MethodB(){
        var_dump('方法组B');
        $this->three->MethodThree();
        $this->four->MethodFour();
    }
}

$a=new Facade();
$a->MethodA();
$a->MethodB();

运行结果

string '方法组A' (length=10)
string '子系统方法一' (length=18)
string '子系统方法二' (length=18)
string '方法组B' (length=10)
string '子系统方法三' (length=18)
string '子系统方法四' (length=18)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值