📄 strategy_patterns.php
字号:
这个就是策略模式(Strategy),将不同情况的算法分拆到不同的类(比如
advanceDiscountor 类),然后调用者(discountor 类)根据具体的情况,用算法类的对
象来处理。策略模式是一种常用的模式,我们可以用它来封装不同情况下的算法代码,方便修改。
但是策略模式,如果乱用,那么就会出来很多多余的算法类,也就是分拆过度。
<?php
//打折接口
interface IDiscountor
{
public function getDiscount();
}
//普通用户打折类
class commonDiscountor implements IDiscountor
{
public function getDiscount()
{
$discount = 1;
return $discount;
}
}
//高级用户打折类
class advanceDiscountor implements IDiscountor
{
public function getDiscount()
{
$discount = 0.9;
return $discount;
}
}
//vip用户打折类
class vipDiscountor implements IDiscountor
{
public function getDiscount()
{
$discount = 0.8;
return $discount;
}
}
//打折类
class discountor
{
public function getDiscount($rank)
{
switch ($rank) {
case 'common':
$discountor = new commonDiscountor();
break;
case 'advance':
$discountor = new advanceDiscountor();
break;
case 'vip':
$discountor = new vipDiscountor();
break;
}
return $discountor->getDiscount();
}
}
$discountor = new discountor();
echo $discountor->getDiscount('advance');
?>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -