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(); //执行策略