当前位置: 首页 > 编程文章 >

PHP设计模式之状态模式定义与用法详解

PHP设计模式之状态模式定义与用法详解

作者:林知时间:2026-07-15 13:39:30浏览:536

状态模式用于解决对象内部状态改变时行为随之变化的问题,通过将状态判断逻辑转移到独立的类中,简化复杂的条件表达式。本文结合开灯关灯和九宫格移动两个实例,演示如何定义接口、实现具体状态类以及上下文类的交互,并展示如何扩展新状态以增强代码的可维护性和可扩展性。

本文目录展开

本内容深入解析了PHP语言中状态模式的定义及其实际应用场景,旨在为开发者提供可参考的实现方案。

状态设计模式的核心概念与应用场景

状态设计模式的核心概念

该模式适用于对象内在状态发生变化从而引发行为改变的场景,使得对象在外部观察者看来仿佛切换了所属的类。

状态模式主要应对的是控制对象状态的条件表达式过于复杂的情况。通过将状态判断逻辑分散到代表不同状态的多个类中,能够有效简化原本冗杂的判断逻辑。

状态模式的应用场景

当对象的行为频繁依赖于条件语句且选项众多时,使用状态模式尤为合适。虽然switch或else-if语句本身并无过错,但当分支过多导致程序结构混乱,或者修改选项成本高昂甚至成为负担时,便需要引入状态模式来优化。

在状态模式中,每个状态都拥有对应的具体类,这些类共同实现一个公共接口。开发者无需追踪对象的控制流,而是从对象当前所处的状态角度来理解和处理业务逻辑。

状态机是一种模型,其核心要素包括不同的状态定义、状态之间的转换关系,以及触发状态改变的特定事件或动作。

以灯光的开闭为例,状态模型的本质可以归纳为三个关键点:

① 状态(例如:关灯状态和开灯状态) ② 变迁(例如:从关灯变为开灯,或从开灯变为关灯) ③ 触发器(例如:用户拨动灯开关的动作)

因此,状态模式的实现必须包含一个参与者来跟踪对象当前的状态。以Light类为例,它需要能够感知并记录当前是处于开启还是关闭状态。

基础示例:灯光开关控制的实现

基础示例:灯光开关控制

文件:Light.php


<?php
class Light
{
  private $offState; //关闭状态
  private $onState;  //开启状态
  private $currentState; //当前状态
  public function __construct()
  {
    $this->offState = new OffState($this);
    $this->onState = new OnState($this);
    //开始状态为关闭状态Off
    $this->currentState = $this->offState;
  }
  //调用状态方法触发器
  public function turnLightOn()
  {
    $this->currentState->turnLightOn();
  }
  public function turnLightOff()
  {
    $this->currentState->turnLightOff();
  }
  //设置当前状态
  public function setState(IState $state)
  {
    $this->currentState = $state;
  }
  //获取状态
  public function getOnState()
  {
    return $this->onState;
  }
  public function getOffState()
  {
    return $this->offState;
  }
}

在Light类的构造函数中,会实例化两个实现了IState接口的对象,分别对应“关”和“开”两种状态。


$this->offState = new OffState($this);
$this->onState = new OnState($this);

这种实例化过程涉及一种称为自引用(self-referral)的技术手段。

构造函数的参数传递的是$this,即Light类自身的引用。这是因为具体的状态类在初始化时需要接收一个Light实例作为参数,以便后续能回调Light的方法。

setState方法用于设置当前状态,它接收一个状态对象作为参数。当某个状态被触发时,该状态对象会向Light类发送信息,从而指定当前的状态。

状态实例的具体实现

首先定义IState接口

文件:IState.php


<?php
interface IState
{
  public function turnLightOn();
  public function turnLightOff();
}

接下来是实现该接口的具体状态类

文件:OnState.php


<?php
class OnState implements IState
{
  private $light;
  public function __construct(Light $light)
  {
    $this->light = $light;
  }
  public function turnLightOn()
  {
    echo "灯已经打开了->不做操作
"; } public function turnLightOff() { echo "灯关闭!看不见帅哥chenqionghe了!
"; $this->light->setState($this->light->getOffState()); } }

文件:OffState.php


<?php
class OffState implements IState
{
  private $light;
  public function __construct(Light $light)
  {
    $this->light = $light;
  }
  public function turnLightOn()
  {
    echo "灯打开!可以看见帅哥chenqionghe了!
"; $this->light->setState($this->light->getOnState()); } public function turnLightOff() { echo "灯已经关闭了->不做操作
"; } }

默认初始状态为OffState,它必须实现IState接口中的turnLightOn和turnLightOff方法。当Light调用turnLightOn时,会输出提示信息(如“灯打开!可以看见帅哥chenqionghe了”),并将当前状态切换为OnState。若调用OffState的turnLightOff方法,则仅提示灯已关闭,无其他状态变更动作。

客户端调用逻辑

Client的所有请求均通过Light类发出,Client与任何状态类之间不存在直接连接,包括IState接口。以下Client代码展示了触发两个状态下所有方法的请求流程。

文件:Client.php


<?php
function __autoload($class_name)
{
  include_once $class_name.'.php';
}
class Client
{
  private $light;
  public function __construct()
  {
    $this->light = new Light();
    $this->light->turnLightOn();
    $this->light->turnLightOn();
    $this->light->turnLightOff();
    $this->light->turnLightOff();
  }
}
$worker = new Client();

状态模式的扩展:增加更多灯光亮度状态

状态的扩展与增加

设计模式的一大优势在于易于修改。状态模式同样具备良好的更新和扩展能力。下面在灯的示例基础上增加两个新状态:更亮(Brighter)和最亮(Brightest)。

此时系统变为4个状态,且转移序列发生改变。'关'(off)状态只能转移到'开'(on)状态;'开'(on)状态不能返回'关',只能转移到'更亮'(brighter)或'最亮'(brightest)状态;只有'最亮'(brightest)状态才能转回'关'状态。

接口的调整

首先需要修改的参与者是接口IState,必须在其中指定用于迁移到brighter和brightest状态的新方法。

文件:IState.php


<?php
interface IState
{
  public function turnLightOn();
  public function turnLightOff();
  public function turnBrighter();
  public function turnBrightest();
}

现在,所有状态类都必须包含这4个方法,并且它们都需要与Light类进行集成。

状态逻辑的改变

当状态设计模式发生变更时,新增的逻辑会对模式的其他方面产生影响。不过,由于每个状态只负责特定的变迁,增加改变的过程相对简单。

四个状态类的实现

文件:OnState.php


<?php
class OnState implements IState
{
  private $light;
  public function __construct(Light $light)
  {
    $this->light = $light;
  }
  public function turnLightOn()
  {
    echo "不合法的操作!
"; } public function turnLightOff() { echo "灯关闭!看不见帅哥chenqionghe了!
"; $this->light->setState($this->light->getOffState()); } public function turnBrighter() { echo "灯更亮了, 看帅哥chenqionghe看得更真切了!
"; $this->light->setState($this->light->getBrighterState()); } public function turnBrightest() { echo "不合法的操作!
"; } }

文件:OffState.php


<?php
class OffState implements IState
{
  private $light;
  public function __construct(Light $light)
  {
    $this->light = $light;
  }
  public function turnLightOn()
  {
    echo "灯打开!可以看见帅哥chenqionghe了!
"; $this->light->setState($this->light->getOnState()); } public function turnLightOff() { echo "不合法的操作!
"; } public function turnBrighter() { echo "不合法的操作!
"; } public function turnBrightest() { echo "不合法的操作!
"; } }

文件:Brighter.php


<?php
class BrighterState implements IState
{
  private $light;
  public function __construct(Light $light)
  {
    $this->light = $light;
  }
  public function turnLightOn()
  {
    echo "不合法的操作!
"; } public function turnLightOff() { echo "不合法的操作!
"; } public function turnBrighter() { echo "不合法的操作!
"; } public function turnBrightest() { echo "灯最亮了, 看帅哥chenqionghe已经帅到无敌!
"; $this->light->setState($this->light->getBrightestState()); } }

文件:Brightest.php


<?php
class BrightestState implements IState
{
  private $light;
  public function __construct(Light $light)
  {
    $this->light = $light;
  }
  public function turnLightOn()
  {
    echo "灯已经打开了->不做操作
"; } public function turnLightOff() { echo "灯关闭!看不见帅哥chenqionghe了!
"; $this->light->setState($this->light->getOffState()); } public function turnBrighter() { echo "不合法的操作!
"; } public function turnBrightest() { echo "不合法的操作!
"; } }

更新Light上下文类

文件:Light.php


<?php
class Light
{
  private $offState; //关闭状态
  private $onState;  //开启状态
  private $brighterState; //更亮状态
  private $brightestState;//最亮状态
  private $currentState; //当前状态
  public function __construct()
  {
    $this->offState = new OffState($this);
    $this->onState = new OnState($this);
    $this->brighterState = new BrighterState($this);
    $this->brightestState = new BrightestState($this);
    //开始状态为关闭状态Off
    $this->currentState = $this->offState;
  }
  //调用状态方法触发器
  public function turnLightOn()
  {
    $this->currentState->turnLightOn();
  }
  public function turnLightOff()
  {
    $this->currentState->turnLightOff();
  }
  public function turnLightBrighter()
  {
    $this->currentState->turnBrighter();
  }
  public function turnLigthBrightest()
  {
    $this->currentState->turnBrightest();
  }
  //设置当前状态
  public function setState(IState $state)
  {
    $this->currentState = $state;
  }
  //获取状态
  public function getOnState()
  {
    return $this->onState;
  }
  public function getOffState()
  {
    return $this->offState;
  }
  public function getBrighterState()
  {
    return $this->brighterState;
  }
  public function getBrightestState()
  {
    return $this->brightestState;
  }
}

更新客户端调用代码


<?php
function __autoload($class_name)
{
  include_once $class_name.'.php';
}
class Client
{
  private $light;
  public function __construct()
  {
    $this->light = new Light();
    $this->light->turnLightOn();
    $this->light->turnLightBrighter();
    $this->light->turnLigthBrightest();
    $this->light->turnLightOff();
    $this->light->turnLigthBrightest();
  }
}
$worker = new Client();

程序运行结果如下

灯打开!可以看见帅哥chenqionghe了! 灯更亮了, 看帅哥chenqionghe看得更真切了! 灯最亮了, 看帅哥chenqionghe已经帅到无敌! 灯关闭!看不见帅哥chenqionghe了! 不合法的操作!

进阶示例:九宫格移动的状态机实现

进阶示例:九宫格移动

九宫格的移动操作分为四种方向:

上(Up) 下(Down) 左(Left) 右(Right)

移动规则要求单元格之间不能沿对角线方向移动,且每次只能从一个单元格移动到相邻的一个单元格。

为了使用状态设计模式构建九宫格移动示例,需要进行以下步骤:

建立状态接口

文件:IMatrix.php


<?php
interface IMatrix
{
  public function goUp();
  public function goDown();
  public function goLeft();
  public function goRight();
}

尽管该状态模式包含9个状态(对应九个单元格),但每个状态最多只需要处理4种变迁(上下左右)。

上下文类的设计

对于状态中的4个变迁或移动方法,上下文类必须提供相应的方法来调用这些变迁,同时还需要完成各个状态对象的实例化工作。

文件:Context.php


<?php
class Context
{
  private $cell1;
  private $cell2;
  private $cell3;
  private $cell4;
  private $cell5;
  private $cell6;
  private $cell7;
  private $cell8;
  private $cell9;
  private $currentState;
  public function __construct()
  {
    $this->cell1 = new Cell1State($this);
    $this->cell2 = new Cell2State($this);
    $this->cell3 = new Cell3State($this);
    $this->cell4 = new Cell4State($this);
    $this->cell5 = new Cell5State($this);
    $this->cell6 = new Cell6State($this);
    $this->cell7 = new Cell7State($this);
    $this->cell8 = new Cell8State($this);
    $this->cell9 = new Cell9State($this);
    $this->currentState = $this->cell5;
  }
  //调用方法
  public function doUp()
  {
    $this->currentState->goUp();
  }
  public function doDown()
  {
    $this->currentState->goDown();
  }
  public function doLeft()
  {
    $this->currentState->goLeft();
  }
  public function doRight()
  {
    $this->currentState->goRight();
  }
  //设置当前状态
  public function setState(IMatrix $state)
  {
    $this->currentState = $state;
  }
  //获取状态
  public function getCell1State()
  {
    return $this->cell1;
  }
  public function getCell2State()
  {
    return $this->cell2;
  }
  public function getCell3State()
  {
    return $this->cell3;
  }
  public function getCell4State()
  {
    return $this->cell4;
  }
  public function getCell5State()
  {
    return $this->cell5;
  }
  public function getCell6State()
  {
    return $this->cell6;
  }
  public function getCell7State()
  {
    return $this->cell7;
  }
  public function getCell8State()
  {
    return $this->cell8;
  }
  public function getCell9State()
  {
    return $this->cell9;
  }
}

具体状态类的实现

9个状态表示九宫格中的不同单元格。为了清晰显示路径,每个状态在被访问时会输出相应的单元格数字,从而直观地展现穿过矩阵的路线。

文件:Cell1State.php


<?php
class Cell1State implements IMatrix
{
  private $context;
  public function __construct(Context $contextNow)
  {
    $this->context = $contextNow;
  }
  public function goLeft()
  {
    echo '不合法的移动!
'; } public function goRight() { echo '走到2
'; $this->context->setState($this->context->getCell2State()); } public function goUp() { echo '不合法的移动!
'; } public function goDown() { echo '走到4
'; $this->context->setState($this->context->getCell4State()); } }

文件:Cell2State.php


<?php
class Cell2State implements IMatrix
{
  private $context;
  public function __construct(Context $contextNow)
  {
    $this->context = $contextNow;
  }
  public function goLeft()
  {
    echo '走到1
'; $this->context->setState($this->context->getCell1State()); } public function goRight() { echo '走到3
'; $this->context->setState($this->context->getCell3State()); } public function goUp() { echo '不合法的移动!
'; } public function goDown() { echo '走到5
'; $this->context->setState($this->context->getCell5State()); } }

文件:Cell3State.php


<?php
class Cell3State implements IMatrix
{
  private $context;
  public function __construct(Context $contextNow)
  {
    $this->context = $contextNow;
  }
  public function goLeft()
  {
    echo '走到2
'; $this->context->setState($this->context->getCell2State()); } public function goRight() { echo '不合法的移动!
'; } public function goUp() { echo '不合法的移动!
'; } public function goDown() { echo '走到6
'; $this->context->setState($this->context->getCell6State()); } }

文件:Cell4State.php


<?php
class Cell4State implements IMatrix
{
  private $context;
  public function __construct(Context $contextNow)
  {
    $this->context = $contextNow;
  }
  public function goLeft()
  {
    echo '不合法的移动!
'; } public function goRight() { echo '走到5
'; $this->context->setState($this->context->getCell5State()); } public function goUp() { echo '走到1
'; $this->context->setState($this->context->getCell1State()); } public function goDown() { echo '走到7
'; $this->context->setState($this->context->getCell7State()); } }

文件:Cell5State.php


<?php
class Cell5State implements IMatrix
{
  private $context;
  public function __construct(Context $contextNow)
  {
    $this->context = $contextNow;
  }
  public function goLeft()
  {
    echo '走到4
'; $this->context->setState($this->context->getCell4State()); } public function goRight() { echo '走到6
'; $this->context->setState($this->context->getCell6State()); } public function goUp() { echo '走到2
'; $this->context->setState($this->context->getCell2State()); } public function goDown() { echo '走到8
'; $this->context->setState($this->context->getCell8State()); } }

文件:Cell6State.php


<?php
class Cell6State implements IMatrix
{
  private $context;
  public function __construct(Context $contextNow)
  {
    $this->context = $contextNow;
  }
  public function goLeft()
  {
    echo '走到5
'; $this->context->setState($this->context->getCell5State()); } public function goRight() { echo '不合法的移动!
'; } public function goUp() { echo '走到3
'; $this->context->setState($this->context->getCell3State()); } public function goDown() { echo '走到9
'; $this->context->setState($this->context->getCell9State()); } }

文件:Cell7State.php


<?php
class Cell7State implements IMatrix
{
  private $context;
  public function __construct(Context $contextNow)
  {
    $this->context = $contextNow;
  }
  public function goLeft()
  {
    echo '不合法的移动!
'; } public function goRight() { echo '走到8
'; $this->context->setState($this->context->getCell8State()); } public function goUp() { echo '走到4
'; $this->context->setState($this->context->getCell4State()); } public function goDown() { echo '不合法的移动!
'; } }

文件:Cell8State.php


<?php
class Cell8State implements IMatrix
{
  private $context;
  public function __construct(Context $contextNow)
  {
    $this->context = $contextNow;
  }
  public function goLeft()
  {
    echo '走到7
'; $this->context->setState($this->context->getCell7State()); } public function goRight() { echo '走到9
'; $this->context->setState($this->context->getCell9State()); } public function goUp() { echo '走到5
'; $this->context->setState($this->context->getCell5State()); } public function goDown() { echo '不合法的移动!
'; } }

文件:Cell9State.php


<?php
class Cell9State implements IMatrix
{
  private $context;
  public function __construct(Context $contextNow)
  {
    $this->context = $contextNow;
  }
  public function goLeft()
  {
    echo '走到8
'; $this->context->setState($this->context->getCell8State()); } public function goRight() { echo '不合法的移动!
'; } public function goUp() { echo '走到6
'; $this->context->setState($this->context->getCell6State()); } public function goDown() { echo '不合法的移动!
'; } }

要有效地使用状态设计模式,真正的难点在于如何将现实世界或模拟世界的逻辑抽象为状态和变迁。

客户端测试代码

下面演示从单元格5开始,依次执行上、右、下、下、左、上的移动操作。

文件:Client.php


<?php
function __autoload($class_name)
{
  include_once $class_name.'.php';
}
class Client
{
  private $context;
  public function __construct()
  {
    $this->context = new Context();
    $this->context->doUp();
    $this->context->doRight();
    $this->context->doDown();
    $this->context->doDown();
    $this->context->doLeft();
    $this->context->doUp();
  }
}
$worker = new Client();

运行结果如下

走到2 走到3 走到6 走到9 走到8 走到5

状态模式在PHP大型项目中的应用价值

状态模式在PHP中的应用

许多人将状态设计模式视为实现模拟器和游戏的主要手段。这确实是其核心目标之一,此外,状态模型(状态引擎)和状态设计模式在PHP大型项目中也有广泛应用。例如Facebook和WordPress等项目,随着新特性和当前状态需求的不断增加,采用可扩展的状态模式进行管理显得尤为重要。

PHP开发人员如何创建包含多个状态的程序,决定了状态模式的使用范围。因此,不仅状态机在游戏和模拟领域应用广泛,只要PHP程序的用户涉及一组有限的状态,开发人员即可考虑使用状态设计模式。

希望上述关于状态模式的阐述能对大家的PHP程序设计工作有所帮助。

上一篇
PHP共享内存用法实例分析

本文介绍PHP中实现进程间通信的两种共享内存扩展:shmop和Semaphore。shmop需开启--enable-shmop参数,提供底层字节操作;Semaphore扩展的sem类函数支持类似key-value格式,使用更便捷。两者不通用,且需注意内存范围、信号量同步及Linux下的ipc/ipcrm命令管理。

下一篇
7个鲜为人知却非常实用的PHP函数

本文介绍7个鲜为人知却非常实用的PHP函数。highlight_string()用于代码高亮显示;str_word_count()统计单词数量;levenshtein()计算编辑距离,适用于身份证修改限制等场景;get_defined_vars()返回所有已定义变量数组,便于调试;escapeshellcmd()转义特殊符号以增强安全性;checkdate()验证日期合法性;php_strip_whitespace()去除注释和空格,便于分析代码结构。

相关文章

更多
PHP设计模式:状态模式(State)详解与实现

状态模式允许对象在内部状态改变时改变其行为,使对象看起来似乎修改了类。本文通过TCP连接和心情变化的例子阐述其核心思想,提供基于接口实现的PHP代码示例,并深入解析其与命令模式在接口方法数量、参数传递方式及消除条件语句方面的异同。

2026.03.16 911
PHP设计模式之状态模式实例分析【星际争霸游戏案例】

状态模式通过将不同状态下的行为封装到独立的类中,有效解决了复杂对象因状态切换而产生的大量条件判断问题。本文以星际争霸中的坦克和机枪兵为例,展示如何利用接口规范状态类,使主体对象仅负责状态流转,从而提升代码的可维护性与扩展性。

2025.07.29 543
PHP设计模式入门之状态模式原理与实现方法分析

自动售卖机在不同状态下可以接受不同动作,同一个按钮也可能因此得到不同结果。原文用这一场景说明将行为交给状态对象的思路。理解实现时,可先画出允许的状态转换,再按投币、选择和退回等操作逐步核对实际状态。

2026.08.13 453
PHP设计模式详解:工厂模式的三种实现与区别

本文介绍PHP中创建型模式之一的工厂模式,涵盖简单工厂、工厂方法和抽象工厂三种形式。通过对比发现,简单工厂在扩展新产品时需修改核心逻辑,违背开闭原则;而工厂方法通过引入具体工厂类,严格遵循开闭原则,便于分工协作。抽象工厂则适用于拥有多条产品线的场景。文章附带完整PHP代码示例,展示各模式的接口定义、实现类及调用方式。

2026.04.17 996
PHP实现状态模式详解:结构、优缺点及应用场景

状态模式允许对象在内部状态改变时改变其行为,使对象看起来似乎修改了它的类。该模式将特定状态相关的行为局部化,使得状态转换显示化,且State对象可被共享。适用于对象行为依赖运行时刻状态或存在庞大多分支条件语句的场景。本文通过PHP示例展示其具体实现方式。

2026.10.25 991
PHP多线程开发中的线程安全与数据竞争问题解决指南

在 PHP 中实现真正的多线程并发,推荐使用 pthread 扩展( PHP 7.1 之前)或 swoole 协程/多进程模型。针对数据竞争问题,核心策略是避免共享可变状态,改用消息队列传递数据,或使用互斥锁保护临界区。

2025.05.18 976

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。