策略模式的簡單實現
- <?php
- namespace Strategy;
- /**
- * 抽象算法類
- * @author struggle
- * @verison 2012-5-29
- */
- abstract class Strategy {
- /**
- * 算法方法
- */
- public abstract function algorithmFunction();
- }
- /**
- * 具體算法類A
- * @author struggle
- * @verison 2012-5-29
- */
- class SpecificStrategyA extends Strategy {
- /**
- * 具體算法A的實現
- */
- public function algorithmFunction(){
- echo '具體算法A<br>';
- }
- }
- /**
- * 具體算法類B
- * @author struggle
- * @verison 2012-5-29
- */
- class SpecificStrategyB extends Strategy {
- /**
- * 具體算法B的實現
- */
- public function algorithmFunction(){
- echo '具體算法B<br>';
- }
- }
- /**
- * 具體算法類C
- * @author struggle
- * @verison 2012-5-29
- */
- class SpecificStrategyC extends Strategy {
- /**
- * 具體算法c的實現
- */
- public function algorithmFunction() {
- echo '具體算法C<br>';
- }
- }
- class Context {
- /**
- * 算法對象
- * @var obj
- */
- private $Strategy ;
- /**
- * 設置算法對象
- * @param Strategy $obj
- */
- public function setStrategy( Strategy $obj){
- $this->Strategy = $obj;
- }
- public function contextInterface(){
- if(!isset($this->Strategy)){
- throw new \Exception('算法對象未設置');
- }
- $this->Strategy->algorithmFunction();
- }
- }
- $context = new Context();
- $context->setStrategy(new SpecificStrategyA());
- $context->contextInterface();
- $context->setStrategy(new SpecificStrategyB());
- $context->contextInterface();
- $context->setStrategy(new SpecificStrategyC());
- $context->contextInterface();
#使用策略與簡單工廠的結合
Context類修改如下:
- class Context{
- /**
- * 算法對象
- * @var obj
- */
- private $Strategy ;
- /**
- * 設置算法對象
- * @param $obj
- */
- public function __construct($type){
- switch (strtoupper($type)){ //全部轉換爲大寫
- case 'A':
- $this->Strategy = new SpecificStrategyA();
- break;
- case 'B':
- $this->Strategy = new SpecificStrategyB();
- break;
- case 'C':
- $this->Strategy = new SpecificStrategyC();
- break;
- default:
- throw new \Exception('未找到算法類 : '.$type);
- }
- }
- public function contextInterface(){
- if(!isset($this->Strategy)){
- throw new \Exception('算法對象未設置');
- }
- $this->Strategy->algorithmFunction();
- }
- }
- $context = new Context('A');
- $context->contextInterface();
- $context = new Context('B');
- $context->contextInterface();
- $context = new Context('c');
- $context->contextInterface();