策略

来源:互联网 发布:c 解析json字符串 编辑:程序博客网 时间:2024/06/08 11:10

叙述

示例

<?php/*** 抽象算法,算法的选择交给Client*/interface TravelStrategy {    public function travelAlgorithm();}class AirPlanelStrategy implements TravelStrategy {    public function travelAlgorithm() {        echo "travel by AirPlain", "\n";    }}class TrainStrategy implements TravelStrategy {    public function travelAlgorithm() {        echo "travel by Train", "\n";    }}class BicycleStrategy implements TravelStrategy {    public function travelAlgorithm() {        echo "travel by Bicycle", "\n";    }}class PersonContext {    private $_strategy=null;    public function __construct(TravelStrategy $strategy) {        $this->_strategy = $strategy;    }    public function setStrategy(TravelStrategy $strategy) {        $this->_strategy = $strategy;    }    public function travel() {        $this->_strategy->travelAlgorithm();    }}/*** 客户端需要自己 选择算法* 工厂模式则是 只需客户传一个标识,就构造一个完成的对象,不需要了解具体的算法,但灵活性低了一点*/class Client {    public static function main() {        $person = new PersonContext(new AirPlanelStrategy());        $person->travel();        $person->setStrategy(new TrainStrategy());        $person->travel();    }}Client::main();
0 0