策略模式:将一组特定的行为和算法封装成类,以适应某种特定的上下文环境,这种模式就是策略模式。
场景:商品的促销活动类型有很多,如:买满减活动、打折、送积分,如何来完成该需求。
<?php Interface Strategy { function sale (); } // 打折策略 class DiscountStrategy implements Strategy { private $money = 0; // 总价 private $rate = 100; // 折扣 public function __construct($money, $rate) { $this->money = $money; $this->rate = $rate; } public function sale () { $money = $this->money - round($this->money * ($this->rate / 100), 2); echo "总价{$this->money},打完折后价格:$money\n"; } } // 送积分 class ScoreStrategy implements Strategy { private $money = 0; // 总价 private $rate = 0; // 兑换比率 public function __construct($money, $rate) { $this->money = $money; $this->rate = $rate; } public function sale () { $score = $this->money * ($this->rate / 100); echo "送积分$score\n"; } } class Page { public function buy () { $obj = $_GET['obj']; echo (new $obj(100,10))->sale(); } } (new Page())->buy();