<?php
//用策略模式 解决商城结算的各种优惠策略
//主要是抽出 算法
//虚基类
abstract class chargeSupper{
//虚函数 抽象出算法函数
abstract function caclCharge();
}
//正常价格类
class chargeNormal{
//构造函数
public function __construct(){
}
//获取价格
public function caclCharge($money){
return $money;
}
}
//打折类
class chargeDiscount{
private $iDiscountNum;
//构造函数
public function __construct($discountNum){
$this->iDiscountNum = $discountNum;
}
//获取价格
public function caclCharge($money){
return $money * $this->iDiscountNum;
}
}
//返利类
class chargeRebate{
private $iThreshold;
private $iRebate;
//构造函数
public function __construct($moneyThreshold , $rebateNum){
$this->iThreshold = $moneyThreshold;
$this->iRebate = $rebateNum;
}
//获取价格
public function caclCharge($money){
$result = $money;
//达到返利的价格
if($money >= $this->iThreshold){
$result = $money - $this->iRebate;
}
return $result;
}
}
//策略实现类
class chargeContext{
private $context = null;
//构造函数
public function __construct($type){
$type = strtolower($type);
switch ($type) {
case 'normal': //正常结算
$this->context = new chargeNormal();
break;
case 'discount': //打折
$this->context = new chargeDiscount(0.8);
break;
case 'rebate': //返利 满300返利100
$this->context = new chargeRebate(300, 100);
break;
default: //默认的话
break;
}
}
//获取价格
public function getTotal($money){
//根据选择的哪个方式 获取价格
return $this->context->caclCharge($money);
}
}
//开始测试
$test = new chargeContext('normal');
$total = $test->getTotal(800);
echo '正常价格 '.$total.'<br />';
$test = new chargeContext('discount');
$total = $test->getTotal(800);
echo '打折 '.$total.'<br />';
$test = new chargeContext('rebate');
$total = $test->getTotal(800);
echo '返利 '.$total.'<br />';