- 封装:把行为用接口封装起来,我们可以把那些经常变化的部分,从当前的类中单独取出来,用接口进行单独的封装。
- 互相替换:我们封装好了接口,通过指定不同的接口实现类进行算法的变化。
<?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
策略模式会立即改变一个算法,当我们使用的类比较简单,但是又相互不关联,只是在特定行为上有所差异的场景下,策略模式就会十分有用。
就在编程领域之外,有许多例子是关于策略模式的。例如:
如果我需要在早晨从家里出发去上班,我可以有几个策略考虑:我可以乘坐地铁,乘坐公交车,走路或其它的途径。每个策略可以得到相同的结果,但是使用了不同的资源。