php之大话策略模式


这里用到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 */



	
  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值