<?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(); // 未定策略,或無效策略