策略模式

/**
 * 策略抽象类 规定策略名称
 */
abstract class strategy {
    abstract function operating();
}
/**
 * 第一个策略
 */
class strategy_1 extends strategy {
    public function operating() {
        echo '第一个策略';
    }
}
/**
 * 第二个策略
 */
class strategy_2 extends strategy {
    public function operating() {
        echo'第二个策略';
    }
}

/**
 * 策略生成器
 */
class strategy_context {
    private $strategy;
    public function __construct($num) {
        //根据不同的条件生成不同的策略
        if($num == 1) {
            $this->strategy = new strategy_1();
        }else{
            $this->strategy = new strategy_2();
        }
    }
    public function operating() {
        return $this->strategy->operating();
    }
}

$strategy_context = new strategy_context(1);
$strategy_context->operating();

策略模式(strategy):
它定义了算法家族,分别将各个算法封装起来,让各个算法之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户端。

posted @ 2015-06-26 14:52  扬空  阅读(200)  评论(0编辑  收藏  举报