设计模式之外观模式php,php设计模式之外观模式

外观模式

为子系统中的一组接口提供一个一致的界面,定义一个高层接口,这个接口使得这一子系统更加容易使用,外观模式又称门面模式

使用外观模式的原因:

1,开发阶段,子系统越来越复杂,增加外观模式提供一个简单的调用接口。

2,维护一个大型遗留系统的时候,可能这个系统已经非常难以维护和扩展,但又包含非常重要的功能,为其开发一个外观类,以便新系统与其交互。

3,外观模式可以隐藏来自调用对象的复杂性。

外观模式的目的在于降低系统的复杂程度

目录结构

|facade #项目根目录

|--Think #核心类库

|----depot.php #仓库类

|----facade.php #外观角色

|----Loder.php #自动加载类

|----orders.php #订单类

|----products.php #商品类

|----user.php #用户系统

|--index.php #单一的入口文件

代码实践

商品类 Think/products.php

/**

* 商品类

*/

namespace Think;

class products{

//查询购买的商品

static function getProduct($product) {

//查看商品库存等信息...

return '商品'.$product;

}

}

订单类 Think/orders.php

/**

* 订单类

*/

namespace Think;

class orders{

static $product;

//添加订单产品

static function pushProduct($product){

self::$product = $product;

}

//添加用户信息,生成订单

static function createOrder($name){

return $name."购买的".self::$product.PHP_EOL;

}

}

用户系统 Think/user.php

/**

* 用户系统

*/

namespace Think;

class user{

//完善用户资料

static function setDate($name){

$data = "用户名为".$name;

return $data;

}

}

仓库类 Think/depot.php

/**

* 仓库类

*/

namespace Think;

class depot {

//发货

static function send($order){

echo $order;

}

}

自动加载类 Think/Loder.php

namespace Think;

class Loder{

static function autoload($class){

require BASEDIR . '/' .str_replace('\\','/',$class) . '.php';

}

}

没有使用外观模式 index.php入口文件

define('BASEDIR',__DIR__);

include BASEDIR . '/Think/Loder.php';

spl_autoload_register('\\Think\\Loder::autoload');

//查询要买的商品

$product = \Think\products::getProduct('帽子');

//提交订单

$orderTmp = \Think\orders::pushProduct($product);

//添加用户信息

$user = \Think\user::setDate('wong');

//生成订单

$order = \Think\orders::createOrder($user);

//仓库发货

$depot = \Think\depot::send($order);

print_r($depot);

输出

用户名为wong购买的商品帽子

使用外观模式 外观角色 Think/facade.php

/**

* 外观角色

*/

namespace Think;

class facade{

static function shop($product,$name){

//查询要买的商品

$product = products::getProduct($product);

//提交订单

$orderTmp = orders::pushProduct($product);

//添加用户信息

$user = user::setDate($name);

//生成订单

$order = orders::createOrder($user);

//仓库发货

$depot = depot::send($order);

return $depot;

}

}

入口文件 index.php

define('BASEDIR',__DIR__);

include BASEDIR . '/Think/Loder.php';

spl_autoload_register('\\Think\\Loder::autoload');

$depot = \Think\facade::shop("裤子","wong");

print_r($depot);

输出

用户名为wong购买的商品裤子

应用实例: 去医院看病,可能要去挂号、门诊、划价、取药,让患者或患者家属觉得很复杂,如果有提供接待人员,只让接待人员来处理,就很方便。

优点: 1、减少系统相互依赖。 2、提高灵活性。 3、提高了安全性。

缺点:不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。

使用场景: 1、为复杂的模块或子系统提供外界访问的模块。 2、子系统相对独立。 3、预防低水平人员带来的风险。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值