[php] 設計模式之 簡單策略模式

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章