//创建状态的抽象类 abstract class State { abstract public function getErrorTip(ReserveResultHandler $r); } //创建状态代表库存不足的类 class NoStockState extends State { public function getErrorTip(ReserveResultHandler $r) { if ($r->statusCode == 1) { echo ‘商品库存不足!!!‘; } else { $r->setState(new NoAreaState()); $r->getErrorTip(); } } } //创建状态代表不再区域范围的类 class NoAreaState extends State { public function getErrorTip(ReserveResultHandler $r) { if ($r->statusCode == 2) { echo ‘活动不在该区域!!!‘; } else { $r->setState(new ExpireSate()); $r->getErrorTip(); } } }
//创建状态代表超时的类
class ExpireSate extends State
{
public function getErrorTip(ReserveResultHandler $r)
{
if ($r->statusCode == 3) {
echo ‘活动已过期!!!‘;
}
}
}
//预占结果处理类 class ReserveResultHandler { public $statusCode; private $current; public function __construct($params) { $this->statusCode = $params; $this->current = new NoStockState(); } public function setState(State $s) { $this->current = $s; } public function getErrorTip() { $this->current->getErrorTip($this); } } //以下代码只是为了测试,真实应用的时候比如预占库存是再下单的时候,那下边的代码就会写在下单流程的逻辑中。前边定义的那些一个类一个文件 $r = new ReserveResultHandler(1); $r->getErrorTip(); //结果:商品库存不足!!! $r->statusCode =2; $r->getErrorTip(); //结果:活动不在该区域!!! $r->statusCode = 3; $r->getErrorTip(); //结果:活动已过期!!!
原文:https://www.cnblogs.com/mantianxing/p/11099258.html