[php] 设计模式之 简单策略模式

本文通过PHP代码实现策略模式,解决电商平台不同结算策略的问题,包括正常价格、打折和返利等,展示了如何抽离算法并根据不同场景选择最优策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?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 />';

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值