2.21. 策略模式(Strategy
定义
- 分离「策略」并使他们之间能互相快速切换。
- 这种模式是一种不错的继承替代方案(替代使用扩展抽象类的方式)
任务
根据订单类型 生成微信支付参数
支付有几种类型(暂时只有两种),
角色订单: 成为vip
商品订单: 购买商品
…
老板: 后续可能会有什么拼团 秒杀…
uml
代码实现
<?php
interface WechatPayInterface
{
public function payData();
}
//商品订单
class GoodOrder implements WechatPayInterface{
public function payData()
{
//创建商品订单...
//Order::Create()...
return ['appid' => '...', 'trade_type' => 'JSAPI'];
}
}
//身份订单 比如 购买 成为vip会员
class RolesOrder implements WechatPayInterface {
public function payData()
{
//购买买vip代码.....
//RolesOrder::Create....
return ['appid' => '...', 'trade_type' => 'JSAPI'];
}
}
class OrderContext
{
protected $order;
public function __construct(WechatPayInterface $order)
{
$this->order = $order;
}
public function pay()
{
return $this->order->payData();
}
}
//创建商品订单
$orderContext = new OrderContext(
new GoodOrder()
);
echo json_encode(
$orderContext->pay()
);
//创建角色订单
$orderContext = new OrderContext(
new RolesOrder()
);
echo json_encode(
$orderContext->pay()
);