<?php /** * 策略模式 * 例如实现算法之间的切换 */ /** * Class APlot * 策略抽象 */ abstract class APlot { abstract public function Use(); } /** * Class PlotA * 策略具体类 */ class PlotA extends APlot { public function Use() { // TODO: Implement Use() method. echo '触发 PlotA 策略' . PHP_EOL; } } /** * Class PlotB * 策略具体类 */ class PlotB extends APlot { public function Use() { // TODO: Implement Use() method. echo '触发 PlotB 策略' . PHP_EOL; } } /** * Class ContextPlot * 策略选择环境。保存策略并执行 */ class ContextPlot { protected $_plot; public function SetPlot(APlot $APlot) { $this->_plot = $APlot; } public function Use() { if (!$this->_plot instanceof APlot){ echo '未定策略,或无效策略'.PHP_EOL; return; } $this->_plot->Use(); } } $context = new ContextPlot(); $context->SetPlot(new PlotA()); $context->Use(); // 触发 PlotA 策略 $context->SetPlot(new PlotB()); $context->Use(); // 触发 PlotB 策略 $context_two = new ContextPlot(); $context_two->Use(); // 未定策略,或无效策略