一、什么是策略模式
将一组特定的业务行为或算法封装成类,可以在运行时更改,以适应某些特定上下文环境,解决各种if else判断,这种模式就是策略模式;
注:如果策略超过4个,考虑用混合模式;
栗子:旅行出游,选择交通工具,每种交通工具都是一种策略
二、策略模式作用
算法可以自由切换,避免使用多重if…else 条件盘点,拓展性好;
三、具体实现
// 交通策略接口
interface TrafficStrategy
{
public function speed();
public function cost();
}
// 公交车
class BusStrategy implements TrafficStrategy
{
public function speed()
{
echo 'speed: 40km/h';
}
public function cost()
{
echo '2元';
}
}
// 出租车
class TaxiStrategy implements TrafficStrategy
{
public function speed()
{
echo 'speed: 60km/h';
}
public function cost()
{
echo '10元';
}
}
class Page
{
protected $strategy;
public function index()
{
echo $this->strategy->speed();
echo $this->strategy->cost();
}
public function setStrategy(TrafficStrategy $strategy)
{
$this->strategy = $strategy;
}
}
$page = new Page;
$strategy = (int)$_GET['traffic'] === 1 ? new TaxiStrategy() : new BusStrategy();
$page->setStrategy($strategy);
$page->index();