class Strategy2 implements IStrategy { function Move(Context $context) : int { $context->counter -= 1; return $context->counter; } } class Context { private $strategy; public $counter = 0; public function setStrategy(IStrategy $strategy) { $this->strategy = $strategy; } public function Algorithm() : int { return $this->strategy->Move($this); } } $context = new Context(); $strategy1 = new Strategy1(); $strategy2 = new Strategy2(); $context->setStrategy($strategy1); for ($i = 0; $i < 30; $i++) { if ($i == 15) { $context->setStrategy($strategy2); } echo "Counter = ", $context->Algorithm(), "\n"; }
<?php /** * Created by PhpStorm. * User: gary * Date: 7/31/16 * Time: 2:53 PM */ namespace DPHP\Strategy; require_once __DIR__ . '/../autoload.php'; $ctx = new Context(); // 打折 echo '===============打xx折===============', PHP_EOL; $ctx->setStrategy(new Discount()); $price = $ctx->cal(300); echo $price, PHP_EOL; // 满xx减免yy echo '===============满xx减免yy===============', PHP_EOL; $ctx->setStrategy(new Reduce()); $price = $ctx->cal(300); echo $price, PHP_EOL; // xx以上打yy折 echo '===============xx以上打yy折===============', PHP_EOL; $ctx->setStrategy(new Promotional()); $price = $ctx->cal(300); echo $price, PHP_EOL;
private $strategy = null; //用于保存策略 /** * 设置指定的策略 * @param Strategy $strategy */ public function setStrategy(Strategy $strategy) { $this->strategy = $strategy; } /** * 执行策略的方法 */ public function index() { if (empty($this->strategy)) { echo 'no stragety'; exit; } //执行策略的方法 $this->strategy->algorithmInterface(); } } //usage: $context = new Context(); $strategyA = new StrategyA(); //实例化策略A $context->setStrategy(); //设置策略A $context->index(); //执行策略