__策略模式:__定义了算法家族,将不同的算法封装具有共同接口的不同的类中,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户
__应用场景:__超市经常根据节日举办各种活动,做打折活动,或者满多少减多少,赠送积分等,都是一系列的算法可以用策略模式实现,减少代码的维护成本。还有电商网站中根据用户的特性,而展现不同的商品等等场景。
首先定义共同接口:
interface Strategy {
public function algorithmInterface();
}
定义不同的实现:
//算法A的实现
class AlgorithmA implements Strategy {
public function algorithmInterface()
{
echo '算法A的实现';
}
}
//算法B的实现
class AlgorithmB implements Strategy {
public function algorithmInterface()
{
echo '算法B的实现';
}
}
//算法C的实现
class AlgorithmC implements Strategy {
public function algorithmInterface()
{
echo '算法C的实现';
}
}
用一个类来维护对Strategy对象的引用:
class Context {
protected $Strategy = null;
//增加类型提示 非Strategy 对象无法传入
public function setStrategy(Strategy $strategy)
{
$this->strategy = $strategy;
}
public function useAlgorithm()
{
$this->strategy->algorithmInterface();
}
}
客户端代码:
//客户端代码
$context = new Context;
$where = 'A';
if ($where === 'A') {
$context->setStrategy(new AlgorithmA());
} elseif ($where === 'B') {
$context->setStrategy(new AlgorithmB);
} elseif ($where === 'C') {
$context->setStrategy(new AlgorithmC);
}
$context->useAlgorithm();