php设计模式 -- 策略模式

策略模式(Strategy pattern)是行为类模式中的一个类型。行为类模式用来说明一个应用是如何运作的。

策略模式:定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。

根据情况传入特定的参数,执行特定的算法,返回特定的数据。

  • 封装:把行为用接口封装起来,我们可以把那些经常变化的部分,从当前的类中单独取出来,用接口进行单独的封装。
  • 互相替换:我们封装好了接口,通过指定不同的接口实现类进行算法的变化。
<?php
/**
 * 定义接口
 */
interface car{
    public function run();
}

/**
 * 接口算法实现
 * @return [type] [description]
 */
class bmwCar implements car{
    public function run(){

        echo "宝马汽车在路上奔驰\n";
    }
}

/**
 * 接口算法实现
 * @return [type] [description]
 */
class audiCar implements car{
    public function run(){

        echo "奥迪汽车在路上奔驰\n";
    }
}

/**
 * 使用不同算法的类
 * @param integer $speed [description]
 */
class chooseCar{
    public $speed;

    function __construct($speed=60){
        $this->speed = $speed;

    }

    function start($brand){
        $car = null;

        switch($brand){
            case "bmw":
                $car = new bmwCar();
                break;
            case "audi":
                $car = new audiCar();
                break;
            default:
                $car = new bmwCar();
        }
        $car->run();
        echo "时速为{$this->speed}km/h";
    }
}

$car = new chooseCar(180);
$car->start("audi");

//输出
奥迪汽车在路上奔驰 时速为180km/h

 

posted @ 2018-12-12 10:57  飞翔的贺兰猪  阅读(125)  评论(0编辑  收藏  举报