記錄策略模式,與簡單工廠模式相互結合,降低代碼之間的耦合 案列:超市收銀軟體系統,需求:滿減,打折。。。各種優惠活動 5個類 ...
記錄策略模式,與簡單工廠模式相互結合,降低代碼之間的耦合
案列:超市收銀軟體系統,需求:滿減,打折。。。各種優惠活動
5個類
- CountP
- Count
- Rabate
- Ret
- Cash
/**
* 父類
*/
abstract class CountP { abstract public function getCash($money); }
/** * Class Count * @package Home\Driver\Sum * 正常計算類 */ class Count extends CountP { public function getCash($money) { return $money; } }
/** * Class Rabate * @package Home\Driver\Sum * 打折計算類 */ class Rabate extends CountP { public $d = 1; public function __construct($dis) { $this->d = $dis; } public function getCash($money) { return $money * $this->d; } }
/** * Class Ret * @package Home\Driver\Sum * 滿減計算類 */ class Ret extends CountP { public $moneyCondition = 0; public $moneyReturn = 0; public function __construct($moneyCondition,$moneyReturn) { $this->moneyCondition = $moneyCondition; $this->moneyReturn = $moneyReturn; } public function getCash($money) { if($money>=$this->moneyCondition){ $money = $money-floor($money/$this->moneyCondition)*$this->moneyReturn; } return $money; } }
/** * Class Cash * @package Home\Driver * 工廠類 */ class Cash{ public $obj = null; public function __construct($type) { switch ($type){ case '正常收費': $this->obj = new Count(); break; case '8折': $this->obj = new Rabate(0.8); break; case '滿300減100': $this->obj = new Ret(300,100); break; default: throw_exception('類型錯誤'); break; } } public function getAcceptCash($money){ return $this->obj->getCash($money); } }
/** * Class SumController * @package Home\Controller * 客戶端 */ class SumController extends Controller { public function index(){ $countSum = new Cash('滿300減100'); $count = $countSum->getAcceptCash(400); echo $count; } }