PHP 设计模式之状态模式
闲来无事,分享下网文
使用状态模式来管理对象的不同状态。在状态模式(State Pattern)中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。
设计订单状态的接口
interface OrderState
{
function pay(); // 支付
function shipping(); // 发货
function cancel(); // 取消订单
}
已支付订单状态的实现
class PaidOrderState implements OrderState
{
const STATE_CODE = 2;
public function pay()
{
throw new Exception('已支付');
}
public function shipping(Order $order)
{
$order->setShipped();
}
public function cancel()
{
throw new Exception('支付后不能取消订单');
}
}
注:每个状态的逻辑都封装在了每个状态对象里面,使用Order的方法来改变订单状态。把每个状态相关的逻辑都封装起来,每当要添加一个新的状态的时候只需要添加一个OrderState接口的一个实现就可以了,状态与状态之间互不依赖。
订单实现
class Order
{
// 订单状态
private $orderState;
// 支付
public function pay()
{
$this->orderState->pay($this);
}
// 发货
public function shipping()
{
$this->orderState->shipping($this);
}
// 取消订单
public function cancel()
{
$this->orderState->cancel($this);
}
// 把订单状态设置成已支付状态
public function setPaid()
{
$this->orderState = new PaidOrderState();
}
// 把订单状态设置成已发货状态
public function setShipped()
{
$this->orderState = new ShippedOrderState();
}
// 把订单状态设置成已取消状态
public function setCanceled()
{
$this->orderState = new CanceledOrderState();
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: