switch ($type) { case "normal": //正常收费 $this->cs = new CashNormal(); break; case "return": //满300反100 $this->cs = new CashReturn("300", "100"); break; case "rebate": //打八折 $this->cs = new CashRebate('0.8'); break; } } //获取最终结算后的金额 public function getResult($srcMoney) { return $this->cs->acceptCash($srcMoney); } } //终端用户调用测试 $cash = new CashContext('return'); echo $cash->getResult('500') . "\n"; //以上满300减100,结果是400 $cash = new CashContext('rebate'); echo $cash->getResult('500') . "\n"; //以上打8折,结果是400 $cash = new CashContext('normal'); echo $cash->getResult('500') . "\n"; //以上正常收款,结果是500
//通过构造方法传入具体的策略 public function __construct($cashSuper) { $this->cashSuper = $cashSuper; } public function getResult($money) { return $this->cashSuper->acceptCash($money); } } //////////////////////////////////////////////////////////////// //客户端代码 $money = 625; //商品总额 //$str='正常收费';//界面中的下拉框 //$str='打折收费';//界面中的下拉框 $str = '返利收费'; //界面中的下拉框 switch ($str) { case '正常收费': $contextObj = new CashContext(new CashNormal()); break; case '打折收费': $contextObj = new CashContext(new CashRebate(0.8)); break; case '返利收费': $contextObj = new CashContext(new CashReturn(500, 10)); break; } $payMoney = $contextObj->getResult($money); var_dump($payMoney);
<?php $cashContext = new CashContext($_POST['type']); $result = $cashContext->ContextResult($_POST['price']); echo $result; class CashContext { private $cs; public function CashContext($type) { switch ($type) { case 'nomal': $this->cs = new CashNomal(); break; case 'rebate': $this->cs = new CashRebate(0.8); break; case 'return': $this->cs = new CashReturn(300, 100); break; } } public function ContextResult($money) { return $this->cs->acceptCash($money); } } abstract class CashSuper { protected abstract function acceptCash($money); }