策略模式(Strategy Pattern):定义一系列算法,将每一个算法封装起来,并让它们可以相互替换。策略模式让算法独立于使用它的客户而变化,也称为政策模式(Policy)。
策略模式包含的角色如下:
Context: 环境类
Strategy: 抽象策略类
ConcreteStrategy: 具体策略类
支付的策略选择
<?php
abstract class zhifu { //抽象策略类
abstract function pay();
}
//微信环境类
class wx extends zhifu {
function pay(){
return 'wx ok';
}
}
//支付宝环境类
class zfb extends zhifu {
function pay(){
return 'zfb ok';
}
}
<?php
//引入对应的支付的类文件
required_once ("")
//具体策略类
class Charge {
//放入支付类的实例
private $charge_obj;
public function choose($type)
{
if ($type == 'zfb') {
//可以进行判断对应的实例是否还存在,不在再实例,即引入注册树
$this->charge_obj = new zfb;
} elseif ($type == 'wx') {
$this->charge_obj = new wx;
} else {
$this->charge_obj = null;
}
}
public function pay()
{
if (is_null($this->charge_obj)) {
exit('初始化错误');
}
$this->charge_obj->pay();
}
}
<?php
//引入策略类文件
required_once ("")
// 获取用户选择的支付方式
$type = trim($_GET['type']);
$Charge = new Charge();
// 初始化支付实例
$Charge->choose($type);
// 调用功能
$Charge->pay();