PHP设计模式之策略模式
策略模式作为一种软件设计模式,指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。比如每个人都要“交个人所得税”,但是“在美国交个人所得税”和“在中国交个人所得税”就有不同的算税方法。
策略模式:
- 定义了一组算法(业务规则);
- 封装了每个算法;
- 这族的算法可互换代替(interchangeable)。
组成
—抽象策略角色: 策略类,通常由一个接口或者抽象类实现。
—具体策略角色:包装了相关的算法和行为。
—环境角色:持有一个策略类的引用,最终给客户端调用。
PHP实现策略模式
<?php
// 抽象活动算法类
abstract class StrategyAbstract
{
public abstract function discount($price);
}
//满减活动算法类
class FullReductionStrategy extends StrategyAbstract
{
public function discount($price)
{
echo '我是满减算法';
}
}
//满折活动算法类
class FullDiscountStrategy extends StrategyAbstract
{
public function discount($price)
{
echo '我是满折算法';
}
}
//满赠活动算法类
class FullGrantStrategy extends StrategyAbstract
{
public function discount($price)
{
echo '我是满赠算法';
}
}
//策略工厂
class StrategyFactory
{
private $strategy;
public function __construct($strategy)
{
$this->strategy = $strategy;
}
public function getDiscount($money)
{
$this->strategy->discount($money);
}
}
$strategy1 = new StrategyFactory(new FullReductionStrategy());
$strategy1->getDiscount(1000);
$strategy2 = new StrategyFactory(new FullDiscountStrategy());
$strategy2->getDiscount(2000);
$strategy3 = new StrategyFactory(new FullGrantStrategy());
$strategy3->getDiscount(1500);
使用场景
- 如果在一个系统里面有许多类,它们之间的区别仅在于它们的行为,那么使用策略模式可以动态地让一个对象在许多行为中选择一种行为。
- 一个系统需要动态地在几种算法中选择一种。
- 如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现。
注意事项: 如果一个系统的策略多于四个,就需要考虑使用混合模式,解决策略类膨胀的问题。