这里用到php的use了。
<meta charset="utf-8">
<?php
//工厂模式和策略模式
function f_cash_context($type)
{
switch ($type)
{
case '正常收费':
return function($money) {
return $money;
};
break;
case '满300返100':
$moneyCondition = 300;
$moneyReturn = 100;
return function($money) use($moneyCondition, $moneyReturn) {
if ($money >= $moneyCondition && $moneyCondition > 0)
{
return $money - intval($money / $moneyCondition) * $moneyReturn;
}
else
{
return $money;
}
};
break;
case '打8折':
$moneyRebate = 0.8;
return function($money) use($moneyRebate) {
return $money * $moneyRebate;
};
break;
default:
exit('无匹配条件');
break;
}
}
$a = 500;
$c = '满300返100';
echo '消费'.$a.'<br/>';
echo $c.'<br/>';
$test = f_cash_context($c);
echo $test($a);
/* f_cash.php */
面向对象
<meta charset="utf-8">
<?php
//工厂模式和策略模式
//抽象类
abstract class CashSuper
{
//抽象方法:收取现金,参数为原价,返回为当前价
abstract function acceptCash($money);
}
//正常收费,继承CashSuper
class CashNormal extends CashSuper
{
function acceptCash($money)
{
return $money;
}
}
//打折收费,继承CashSuper
class CashRebate extends CashSuper
{
private $moneyRebate = 0.0;
//初始化时,必需要输入折扣率,如八折,就是0.8
public function CashRebate($moneyRebate_)
{
$this->moneyRebate = double($moneyRebate_);
}
public function acceptCash($money)
{
return $money * $this->moneyRebate;
}
}
//返利收费,继承CashSuper
class CashReturn extends CashSuper
{
private $moneyCondition = 0.0;
private $moneyReturn = 0.0;
//初始化时必须要输入返利条件和返利值,比如满300返100,则moneyCondition为300,moneyReturn为100
public function CashReturn($moneyCondition, $moneyReturn)
{
$this->moneyCondition = (double)$moneyCondition;
$this->moneyReturn = (double)$moneyReturn;
}
public function acceptCash($money)
{
//若大于返利条件,则需要减去返利值
if ($money >= $this->moneyCondition and $this->moneyCondition > 0)
{
return $money - (int)($money / $this->moneyCondition) * $this->moneyReturn;
}
else
{
return $money;
}
}
}
//现金收取工厂
class CashContext
{
private $cs = null;
//根据条件返回相应的对象
public function CashContext($type)
{
switch ($type)
{
case '正常收费':
$cs0 = new CashNormal();
$this->cs = $cs0;
break;
case '满300返100':
$cr1 = new CashReturn('300', '100');
$this->cs = $cr1;
break;
case '打8折':
$cr2 = new CashRebate('0.8');
$this->cs = $cr2;
break;
}
}
public function GetResult($money)
{
return $this->cs->acceptCash($money);
}
}
$a = 500;
$c = '满300返100';
echo '消费'.$a.'<br/>';
echo $c.'<br/>';
$test = new CashContext($c);
echo $test->GetResult($a);
/* c_cash.php */