状态模式简介与自动售货机场景
本实例详细解析了PHP设计模式中状态模式的核心理念与具体落地方式,旨在为读者提供实用的参考指南。
以常见的自动饮料售卖机为例,用户投入货币并选择饮品后,机器会吐出商品。若要通过编程模拟这一过程,该如何构建系统架构?
为了理清逻辑,我们首先需要明确该自动售货机所具备的几种核心状态。
第一种状态为“无币状态”,即用户尚未投入硬币或纸币。
第二种状态为“有币状态”,表示机器已接收货币,等待用户操作。
第三种状态为“售出状态”,指机器正在执行出货动作。
第四种状态为“售罄状态”,意味着库存已空,无法继续销售。
明确了上述四种状态后,我们可以着手编写初步的代码实现。
主要逻辑文件名为 JuiceMachine.php。
<?php
/**
* 饮料机
* @author ben
*
*/
class JuiceMachine{
/**
* 糖果机一共存在四种状态:没钱,有钱,成功售出以及销售一空
*
* 没钱的状态
* @var INT
*/
const NOMONEY = 0;
/**
* 有钱的状态
* @var INT
*/
const HASMONEY = 1;
/**
* 成功售出的状态
* @var INT
*/
const SOLD = 2;
/**
* 销售一空的状态
* @var INT
*/
const SOLDOUT = 3;
/**
* 记录糖果机当前的状态,初始化状态为售空
* @var INT
*/
private $_state = JuiceMachine::SOLDOUT;
/**
* 该变量用于记录饮料机中饮料的数量
*/
private $_count;
/**
* 构造方法,最主要是用来初始化count和state属性的
*/
public function __construct($count){
$this->_count = $count;
//当饮料机中的饮料数量大于零时,将饮料机的状态重置为没有钱的状态。
if($this->_count > 0){
$this->_state = JuiceMachine::NOMONEY;
}
}
/**
* 投入硬币
*/
public function insertCoin(){
if($this->_state == JuiceMachine::HASMONEY ){
echo "you can't insert another coin!
";
}elseif($this->_state == JuiceMachine::NOMONEY){
echo "you just insert a coin
";
$this->_state = JuiceMachine::HASMONEY;
}elseif($this->_state == JuiceMachine::SOLD){
echo "wait a minute, we are giving you a bottle of juice
";
}elseif($this->_state == JuiceMachine::SOLDOUT){
echo "you can't insert coin, the machine is already soldout
";
}
}
/**
* 退回硬币
*/
public function retreatCoin(){
if($this->_state == JuiceMachine::HASMONEY ){
echo "coin return!
";
$this->_state = JuiceMachine::NOMONEY;
}elseif($this->_state == JuiceMachine::NOMONEY){
echo "you have'nt inserted a coin yet
";
}elseif($this->_state == JuiceMachine::SOLD){
echo "sorry, you already clicked the botton
";
}elseif($this->_state == JuiceMachine::SOLDOUT){
echo "you have'nt inserted a coin yet
";
}
}
/**
* 点击饮料对应的按钮
*/
public function clickButton(){
if($this->_state == JuiceMachine::HASMONEY ){
echo "you clicked, we are giving you a bottle of juice...
";
$this->_state = JuiceMachine::SOLD; //改变饮料机的状态为售出模式
$this->dispend();
}elseif($this->_state == JuiceMachine::NOMONEY){
echo "you clicked,but you hav'nt inserted a coin yet
";
}elseif($this->_state == JuiceMachine::SOLD){
echo "click twice does'nt get you two bottle of juice
";
}elseif($this->_state == JuiceMachine::SOLDOUT){
echo "you clicked, but the machine is already soldout
";
}
}
/**
* 发放饮料
*/
public function dispend(){
if($this->_state == JuiceMachine::HASMONEY ){
echo "please click the button first
";
}elseif($this->_state == JuiceMachine::NOMONEY){
echo "you need to pay first
";
}elseif($this->_state == JuiceMachine::SOLD){
echo "now you get you juice
";
//饮料机中的饮料数量减一
$this->_count--;
if($this->_count <= 0){
echo "opps, runing out of juice
";
//如果这时饮料机中没有饮料了,将饮料机的状态重置为销售一空
$this->_state = JuiceMachine::SOLDOUT;
}else{
//将饮料机的状态重置为没有钱
$this->_state = JuiceMachine::NOMONEY;
}
}elseif($this->_state == JuiceMachine::SOLDOUT){
//其实这种情况不应该出现
echo "opps, it appears that we don't have any juice left
";
}
}
}
入口调用文件命名为 index.php。
<?php
require_once 'JuiceMachine.php';
$juiceMachine = new JuiceMachine(1);
$juiceMachine->insertCoin();
$juiceMachine->clickButton();
执行上述代码后的控制台输出结果如下。
you just insert a coin you clicked, we are giving you a bottle of juice... now you get you juice opps, runing out of juice
尽管当前程序能正常运行,但其中充斥的多重if-else判断结构暗示着潜在的代码异味。当业务需求变更时,例如老板要求点击按钮时有10%的概率赠送第二瓶饮料,我们需要新增一个状态。此时若直接修改原有代码,不仅容易引发回归Bug,还会导致系统难以维护。状态模式正是解决此类问题的利器。
根据GoF的定义,状态模式的核心在于:当一个对象的内在状态改变时,允许其改变外部行为,使得该对象看起来像是改变了所属的类。
其通用的UML类图结构如下所示。

结合本项目实际,具体的类图关系如下。

以下是基于状态模式重构后的具体实现代码。
抽象状态接口文件 State.php。
<?php
interface State{
/**
* 插入硬币
*/
public function insertCoin();
/**
* 回退硬币
*/
public function retreatCoin();
/**
* 点击按钮
*/
public function clickButton();
/**
* 发放饮料
*/
public function dispend();
}
无币状态实现类 NomoneyState.php。
<?php
require_once 'State.php';
class NomoneyState implements State{
/**
* 饮料机的实例
*
* @var object
*/
private $_juiceMachine;
/**
* 构造方法,主要用于初始化饮料机实例
*
*/
public function __construct($juiceMachine){
$this->_juiceMachine = $juiceMachine;
}
/* (non-PHPdoc)
* @see State::insertCoin()
*/
public function insertCoin()
{
// TODO Auto-generated method stub
echo "you just insert a coin
";
//将饮料机的状态切换成有钱的状态
$this->_juiceMachine->setState($this->_juiceMachine->getHasmoneyState());
}
/* (non-PHPdoc)
* @see State::retreatCoin()
*/
public function retreatCoin()
{
// TODO Auto-generated method stub
echo "you have'nt inserted a coin yet
";
}
/* (non-PHPdoc)
* @see State::clickButton()
*/
public function clickButton()
{
// TODO Auto-generated method stub
echo "you clicked,but you hav'nt inserted a coin yet
";
}
/* (non-PHPdoc)
* @see State::dispend()
*/
public function dispend()
{
// TODO Auto-generated method stub
echo "you need to pay first
";
}
}
有币状态实现类 HasmoneyState.php。
<?php
require_once 'State.php';
class HasmoneyState implements State
{
/**
* 饮料机的实例
*
* @var object
*/
private $_juiceMachine;
/**
* 构造方法,主要用于初始化饮料机实例
*/
public function __construct($juiceMachine)
{
$this->_juiceMachine = $juiceMachine;
}
/*
* (non-PHPdoc) @see State::insertCoin()
*/
public function insertCoin()
{
// TODO Auto-generated method stub
echo "you can't insert another coin!
";
}
/*
* (non-PHPdoc) @see State::retreatCoin()
*/
public function retreatCoin()
{
// TODO Auto-generated method stub
echo "coin return!
";
$this->_juiceMachine->setState($this->_juiceMachine->getNomoneyState());
}
/*
* (non-PHPdoc) @see State::clickButton()
*/
public function clickButton()
{
// TODO Auto-generated method stub
echo "you clicked, we are giving you a bottle of juice...
";
// 改变饮料机的状态为售出模式
$rand = mt_rand(0, 0);
// 当随机数为0(即1/10的概率)并且饮料机中还有1瓶以上的饮料时
if ($rand == 0 && $this->_juiceMachine->getCount() > 1) {
$this->_juiceMachine->setState($this->_juiceMachine->getWinnerState());
} else {
$this->_juiceMachine->setState($this->_juiceMachine->getSoldState());
}
}
/*
* (non-PHPdoc) @see State::dispend()
*/
public function dispend()
{
// TODO Auto-generated method stub
echo "please click the button first
";
}
}
售罄状态实现类 SoldoutState.php。
<?php
require_once 'State.php';
class SoldoutState implements State{
/**
* 饮料机的实例
*
* @var object
*/
private $_juiceMachine;
/**
* 构造方法,主要用于初始化饮料机实例
*
*/
public function __construct($juiceMachine){
$this->_juiceMachine = $juiceMachine;
}
/* (non-PHPdoc)
* @see State::insertCoin()
*/
public function insertCoin()
{
// TODO Auto-generated method stub
echo "you can't insert coin, the machine is already soldout
";
}
/* (non-PHPdoc)
* @see State::retreatCoin()
*/
public function retreatCoin()
{
// TODO Auto-generated method stub
echo "you have'nt inserted a coin yet
";
}
/* (non-PHPdoc)
* @see State::clickButton()
*/
public function clickButton()
{
// TODO Auto-generated method stub
echo "you clicked, but the machine is already soldout
";
}
/* (non-PHPdoc)
* @see State::dispend()
*/
public function dispend()
{
// TODO Auto-generated method stub
echo "opps, it appears that we don't have any juice left
";
}
}
售出状态实现类 SoldState.php。
<?php
require_once 'State.php';
class SoldState implements State{
/**
* 饮料机的实例
*
* @var object
*/
private $_juiceMachine;
/**
* 构造方法,主要用于初始化饮料机实例
*
*/
public function __construct($juiceMachine){
$this->_juiceMachine = $juiceMachine;
}
/* (non-PHPdoc)
* @see State::insertCoin()
*/
public function insertCoin()
{
// TODO Auto-generated method stub
echo "wait a minute, we are giving you a bottle of juice
";
}
/* (non-PHPdoc)
* @see State::retreatCoin()
*/
public function retreatCoin()
{
// TODO Auto-generated method stub
echo "sorry, you already clicked the botton
";
}
/* (non-PHPdoc)
* @see State::clickButton()
*/
public function clickButton()
{
// TODO Auto-generated method stub
echo "click twice does'nt get you two bottle of juice
";
}
/* (non-PHPdoc)
* @see State::dispend()
*/
public function dispend()
{
$this->_juiceMachine->decJuice();
if($this->_juiceMachine->getCount() <= 0){
echo "opps, runing out of juice
";
//如果这时饮料机中没有饮料了,将饮料机的状态重置为销售一空
$this->_juiceMachine->setState($this->_juiceMachine->getSoldoutState());
}else{
//将饮料机的状态重置为没有钱
$this->_juiceMachine->setState($this->_juiceMachine->getNomoneyState());
}
}
}
中奖状态实现类 WinnerState.php(用于处理赠送逻辑)。
<?php
require_once 'State.php';
class WinnerState implements State
{
/**
* 饮料机的实例
*
* @var object
*/
private $_juiceMachine;
/**
* 构造方法,主要用于初始化饮料机实例
*/
public function __construct($juiceMachine)
{
$this->_juiceMachine = $juiceMachine;
}
/*
* (non-PHPdoc) @see State::insertCoin()
*/
public function insertCoin()
{
// TODO Auto-generated method stub
echo "wait a minute, we are giving you a bottle of juice
";
}
/*
* (non-PHPdoc) @see State::retreatCoin()
*/
public function retreatCoin()
{
// TODO Auto-generated method stub
echo "sorry, you already clicked the botton
";
}
/*
* (non-PHPdoc) @see State::clickButton()
*/
public function clickButton()
{
// TODO Auto-generated method stub
echo "click twice does'nt get you two bottle of juice
";
}
/*
* (non-PHPdoc) @see State::dispend()
*/
public function dispend()
{
echo "you are a winner! you get two bottle of juice!
";
$this->_juiceMachine->decJuice();
if ($this->_juiceMachine->getCount() > 0) {
$this->_juiceMachine->decJuice();
if ($this->_juiceMachine->getCount() <= 0) {
echo "opps, runing out of juice
";
// 如果这时饮料机中没有饮料了,将饮料机的状态重置为销售一空
$this->_juiceMachine->setState($this->_juiceMachine->getSoldoutState());
} else {
// 将饮料机的状态重置为没有钱
$this->_juiceMachine->setState($this->_juiceMachine->getSoldoutState());
}
} else {
echo "opps, runing out of juice
";
// 如果这时饮料机中没有饮料了,将饮料机的状态重置为销售一空
$this->_juiceMachine->setState($this->_juiceMachine->getSoldoutState());
}
}
}
上下文环境类 JuiceMachine.php。
<?php
require_once './state/NomoneyState.php';
require_once './state/HasmoneyState.php';
require_once './state/SoldState.php';
require_once './state/SoldoutState.php';
require_once './state/WinnerState.php';
class JuiceMachine
{
/**
* 记录糖果机当前的状态,初始化状态为售空
*
* @var object
*/
private $_state;
/**
* 该变量用于记录饮料机中饮料的数量
*/
private $_count;
/**
* 构造方法,最主要是用来初始化count和state属性的
*/
public function __construct($count)
{
$this->_state = new SoldoutState($this);
$this->_count = $count;
// 当饮料机中的饮料数量大于零时,将饮料机的状态重置为没有钱的状态。
if ($this->_count > 0) {
$this->_state = new NomoneyState($this);
}
}
/*
* (non-PHPdoc) @see State::insertCoin()
*/
public function insertCoin()
{
// TODO Auto-generated method stub
$this->_state->insertCoin();
}
/*
* (non-PHPdoc) @see State::retreatCoin()
*/
public function retreatCoin()
{
// TODO Auto-generated method stub
$this->_state->retreatCoin();
}
/*
* (non-PHPdoc) @see State::clickButton()
*/
public function clickButton()
{
$this->_state->clickButton();
//其实发放糖果是在用户点击完按钮后机器内部进行的所有没有必要再写一个dispend方法
$this->_state->dispend();
}
/**
* 设置糖果机的状态
*
* @param State $state
*/
public function setState(State $state)
{
$this->_state = $state;
}
/**
* 获取没有钱的状态
*/
public function getNomoneyState(){
return new NomoneyState($this);
}
/**
* 获取有钱的状态
*/
public function getHasmoneyState(){
return new HasmoneyState($this);
}
/**
* 获取售出的状态
*/
public function getSoldState(){
return new SoldState($this);
}
/**
* 获取销售一空的状态
*/
public function getSoldoutState(){
return new SoldoutState($this);
}
/**
* 获取幸运者的状态
*/
public function getWinnerState(){
return new WinnerState($this);
}
/**
* 获取饮料机中饮料的数量
*/
public function getCount(){
return $this->_count;
}
/**
* 将饮料数量减一
*/
public function decJuice(){
echo "now you get you juice
";
//饮料机中的饮料数量减一
$this->_count--;
}
}
测试入口文件 index.php。
<?php
require_once 'JuiceMachine.php';
$juiceMachine = new JuiceMachine(2);
$juiceMachine->insertCoin();
$juiceMachine->clickButton();
希望上述关于PHP程序设计的内容能对各位开发者有所助益。