编程中的设计模式之状态模式
2020-10-13 本文已影响0人
phpworkerman
定义
状态模式(State Pattern)当一个对象的内部状态改变时允许改变其行为,这个对象看起来像是改变了其他类,属于行为型模式。
代码示例
在商城系统中,一个订单完成一个流程处理需求精力多个状态修改,这里只列举几种常见状态:未支付、已支付、已发货、已完成,抽象状态对象,通过这四个状态的具体对象实现,由公司类初始化时使用未支付的对象,传入不同的状态可以产生不同的行为。
<?php
abstract class State
{
abstract public function action($company);
}
class Pending extends State
{
public function action($company)
{
if($company->getOrderStatus() == 'pending'){
echo '当前订单未支付';
}else{
$company->setState(new PaymentSuccess());
$company->processOrder();
}
}
}
class PaymentSuccess extends State
{
public function action($company)
{
if($company->getOrderStatus() == 'payment_success'){
echo '订单已支付';
}else{
$company->setState(new Shipped());
$company->processOrder();
}
}
}
class Shipped extends State
{
public function action($company)
{
if($company->getOrderStatus() == 'shipped'){
echo '订单已发货';
}else{
$company->setState(new Completed());
$company->processOrder();
}
}
}
class Completed extends State
{
public function action($company)
{
if($company->getOrderStatus() == 'completed'){
echo '订单已完成';
}else{
echo '未知状态';
exit;
}
}
}
class Company
{
private $state;
public $orderStatus;
public function __construct()
{
$this->state = new Pending();
$this->orderStatus = 'shipped';
}
public function setState($state)
{
$this->state = $state;
}
public function getState()
{
return $this->state;
}
public function getOrderStatus()
{
return $this->orderStatus;
}
public function processOrder()
{
$this->state->action($this);
}
}
class DemoPattern
{
public function handle()
{
$company = new Company();
$company->processOrder();
//修改状态再次判断
$company->orderStatus = 'completed';
$company->processOrder();
}
}
$demoPattern = new DemoPattern();
$demoPattern->handle();
总结
如果一个对象中存在很多的状态判断,可以使用该模式把每个状态定义为一个新的子类,减少单个判断语句对整体的影响。