【设计模式-行为型】状态模式

ops/2025/1/24 10:15:46/

一、什么是状态模式

        什么是状态模式呢,这里我举一个例子来说明,在自动挡汽车中,挡位的切换是根据驾驶条件(如车速、油门踏板位置、刹车状态等)自动完成的。这种自动切换挡位的过程可以很好地用状态模式来描述。状态模式(State Pattern) 是一种行为型设计模式,它允许一个对象在其内部状态发生变化时(加速或者减速)改变其行为(换挡)。状态模式的核心思想是将对象的行为封装在不同的状态类中,使得对象的行为随着状态的改变而改变。这种模式特别适用于对象的行为依赖于其内部状态的场景。

二、为什么使用状态模式

  1. 清晰的职责划分:代码结构清晰,每个状态类的职责单一,易于理解和维护。例如,在自动挡汽车中,每个挡位的行为都封装在独立的状态类中,职责划分明确。

  2. 动态改变行为:减少了复杂的条件分支(如 if-elseswitch-case),使代码更加简洁和可读。例如,在自动挡汽车中,换挡逻辑由状态机自动处理,无需在主逻辑中写复杂的条件判断。

  3. 扩展性:符合开闭原则(对扩展开放,对修改封闭)。例如,在自动挡汽车中,新增一个挡位(如6挡)时,只需添加一个新的状态类,无需修改现有的换挡逻辑。

  4. 低耦合:状态类和上下文类之间的依赖关系减少,提高了代码的灵活性和可维护性。例如,在自动挡汽车中,Car 类与各个挡位状态类通过 GearState 接口交互,降低了耦合度。

  5. 适应复杂状态逻辑:能够清晰地表达状态转换逻辑,避免代码混乱。例如,在自动挡汽车中,换挡逻辑可能涉及多种条件(如车速、油门位置等),状态机模式能够清晰地表达这些逻辑。

三、状态模式的示例

3.1 状态模式示例及角色

1. State:定义状态接口(行为)

定义了所有挡位状态的通用接口,包含所有挡位共有的方法,例如加速、减速等

public interface GearState {void accelerate(Car car); // 加速时的行为void decelerate(Car car); // 减速时的行为
}

2. ConcreteState:实现具体状态类(档位)

每个挡位(如1挡、2挡、3挡、4挡、5挡等)都实现状态接口,并定义在该挡位下的行为。

public class FirstGear implements GearState {@Overridepublic void accelerate(Car car) {System.out.println("当前1档:加速...");car.setState(new SecondGear()); // 切换到2挡}@Overridepublic void decelerate(Car car) {System.out.println("当前1档:减速...");car.setState(new NeutralGear()); // 切换到空挡}
}public class SecondGear implements GearState {@Overridepublic void accelerate(Car car) {System.out.println("当前2档:加速...");car.setState(new ThirdGear()); // 切换到3挡}@Overridepublic void decelerate(Car car) {System.out.println("当前2档:减速...");car.setState(new FirstGear()); // 切换到1挡}
}public class ThirdGear implements GearState {@Overridepublic void accelerate(Car car) {System.out.println("当前3档:加速...");car.setState(new FourthGear()); // 切换到4挡}@Overridepublic void decelerate(Car car) {System.out.println("当前3档:减速...");car.setState(new SecondGear()); // 切换到2挡}
}public class FourthGear implements GearState {@Overridepublic void accelerate(Car car) {System.out.println("当前4档:加速...");car.setState(new FifthGear()); // 切换到5挡}@Overridepublic void decelerate(Car car) {System.out.println("当前1档:减速...");car.setState(new ThirdGear()); // 切换到3挡}
}public class FifthGear implements GearState {@Overridepublic void accelerate(Car car) {System.out.println("当前5档:加速...");// 保持在5挡}@Overridepublic void decelerate(Car car) {System.out.println("当前5档:减速...");car.setState(new FourthGear()); // 切换到4挡}
}public class NeutralGear implements GearState {@Overridepublic void accelerate(Car car) {System.out.println("当前空档:加速...");car.setState(new FirstGear()); // 切换到1挡}@Overridepublic void decelerate(Car car) {System.out.println("当前空档:减速...");// 保持在空挡}
}

3、Context(上下文):(当前车辆,记录当前状态)

上下文可以被视为汽车的驾驶系统,它包含当前挡位的状态,并根据驾驶员的操作切换挡位

public class Car {private GearState currentState;public Car() {this.currentState = new NeutralGear(); // 初始状态为空挡}public void setState(GearState state) {this.currentState = state;}public void accelerate() {currentState.accelerate(this);}public void decelerate() {currentState.decelerate(this);}
}

4、场景(开车)

public class Main {public static void main(String[] args) {Car car = new Car();car.accelerate(); // 初始状态为空挡,加速后切换到1挡car.accelerate(); // 当前状态为1挡,加速后切换到2挡car.accelerate(); // 当前状态为2挡,加速后切换到3挡car.decelerate(); // 当前状态为3挡,减速后切换到2挡car.decelerate(); // 当前状态为2挡,减速后切换到1挡car.decelerate(); // 当前状态为1挡,减速后切换到空挡}
}//输出
当前0档:加速...
当前1档:加速...
当前2档:加速...
当前3档:加速...
当前3档:减速...
当前2档:减速...
当前1档:减速...
当前0档:减速...

3.2 在JAVA开发中常用的Spring状态机

        在Spring框架中,可以使用Spring State Machine来实现状态机模式。Spring State Machine是一个功能强大的状态机框架,支持定义状态、事件和状态转换,并且可以与Spring生态系统无缝集成。在实际开发中,可能使用Spring框架比较多,一般都是直接使用现成的Spring State Machine 来实现状态模式

1、集成依赖包

<dependency><groupId>org.springframework.statemachine</groupId><artifactId>spring-statemachine-core</artifactId><version>2.1.3.RELEASE</version>
</dependency>

2、定义状态和事件

//车辆档位枚举类
public enum CarState {NEUTRAL,     //空挡FIRST_GEAR,  //一档SECOND_GEAR, //二挡THIRD_GEAR,  //三挡FOURTH_GEAR, //四挡FIFTH_GEAR;   //五档
}//车辆行为枚举类
public enum CarEvent {ACCELERATE,     //加速行为DECELERATE;     //减速行为
}

3、配置状态机

@Configuration
@EnableStateMachine(name="carStateMachine")
public class CarStateMachineConfig extends StateMachineConfigurerAdapter<CarState, CarEvent> {public void configure(StateMachineStateConfigurer<CarState, CarEvent> states) throws Exception {states.withStates().initial(CarState.NEUTRAL).states(EnumSet.allOf(CarState.class));}@Overridepublic void configure(StateMachineTransitionConfigurer<CarState, CarEvent> states) throws Exception {states.withExternal().source(CarState.NEUTRAL).target(CarState.FIRST_GEAR).event(CarEvent.ACCELERATE).and().withExternal().source(CarState.FIRST_GEAR).target(CarState.SECOND_GEAR).event(CarEvent.ACCELERATE).and().withExternal().source(CarState.SECOND_GEAR).target(CarState.THIRD_GEAR).event(CarEvent.ACCELERATE).and().withExternal().source(CarState.THIRD_GEAR).target(CarState.FOURTH_GEAR).event(CarEvent.ACCELERATE).and().withExternal().source(CarState.FOURTH_GEAR).target(CarState.FIFTH_GEAR).event(CarEvent.ACCELERATE).and().withExternal().source(CarState.FIFTH_GEAR).event(CarEvent.ACCELERATE) // No change.and().withExternal().source(CarState.FIFTH_GEAR).target(CarState.FOURTH_GEAR).event(CarEvent.DECELERATE).and().withExternal().source(CarState.FOURTH_GEAR).target(CarState.THIRD_GEAR).event(CarEvent.DECELERATE).and().withExternal().source(CarState.THIRD_GEAR).target(CarState.SECOND_GEAR).event(CarEvent.DECELERATE).and().withExternal().source(CarState.SECOND_GEAR).target(CarState.FIRST_GEAR).event(CarEvent.DECELERATE).and().withExternal().source(CarState.FIRST_GEAR).target(CarState.NEUTRAL).event(CarEvent.DECELERATE);}// 配置状态机持久化@Beanpublic DefaultStateMachinePersister machinePersister() {return new DefaultStateMachinePersister<>(new StateMachinePersist<Object, Object, Car>() {@Overridepublic void write(StateMachineContext<Object, Object> stateMachineContext, Car car) throws Exception {//持久化操作。可以通过任何形式进行持久化。redis 、 mongodb、mysql,ecache}@Overridepublic StateMachineContext<Object, Object> read(Car car) throws Exception {// 从持久化组件里进行读取return new DefaultStateMachineContext(car.getCarState(), null, null, null);}});}
}

4、定义状态监听器

        在Spring State Machine中,可以通过@WithStateMachine注解和@OnTransition注解来定义状态监听器。这些监听器会在状态转换时被触发。

// 监听器是监听到 action 后进行状态的一个变更。
@Slf4j
@Component("carStateListener")
@WithStateMachine(name="carStateMachine")
public class CarStateListener {@OnTransition(source = "NEUTRAL", target = "FIRST_GEAR")public boolean onAccelerateFromNeutral(Message<CarEvent> message) {log.info("Accelerating from NEUTRAL to FIRST_GEAR");Car car = (Car) message.getHeaders().get("car");car.setCarState(CarState.FIRST_GEAR);return true;}@OnTransition(source = "FIRST_GEAR", target = "SECOND_GEAR")public boolean onAccelerateFromFirstGear(Message<CarEvent> message) {log.info("Accelerating from FIRST_GEAR to SECOND_GEAR");Car car = (Car) message.getHeaders().get("car");car.setCarState(CarState.SECOND_GEAR);return true;}@OnTransition(source = "SECOND_GEAR", target = "THIRD_GEAR")public boolean onAccelerateFromSecondGear(Message<CarEvent> message) {log.info("Accelerating from SECOND_GEAR to THIRD_GEAR");Car car = (Car) message.getHeaders().get("car");car.setCarState(CarState.THIRD_GEAR);return true;}@OnTransition(source = "THIRD_GEAR", target = "FOURTH_GEAR")public boolean onAccelerateFromThirdGear(Message<CarEvent> message) {log.info("Accelerating from THIRD_GEAR to FOURTH_GEAR");Car car = (Car) message.getHeaders().get("car");car.setCarState(CarState.FOURTH_GEAR);return true;}@OnTransition(source = "FOURTH_GEAR", target = "FIFTH_GEAR")public boolean onAccelerateFromFourthGear(Message<CarEvent> message) {log.info("Accelerating from FOURTH_GEAR to FIFTH_GEAR");Car car = (Car) message.getHeaders().get("car");car.setCarState(CarState.FIFTH_GEAR);return true;}@OnTransition(source = "FIFTH_GEAR", target = "FOURTH_GEAR")public boolean onDecelerateFromFifthGear(Message<CarEvent> message) {log.info("Decelerating from FIFTH_GEAR to FOURTH_GEAR");Car car = (Car) message.getHeaders().get("car");car.setCarState(CarState.FOURTH_GEAR);return true;}@OnTransition(source = "FOURTH_GEAR", target = "THIRD_GEAR")public boolean onDecelerateFromFourthGear(Message<CarEvent> message) {log.info("Decelerating from FOURTH_GEAR to THIRD_GEAR");Car car = (Car) message.getHeaders().get("car");car.setCarState(CarState.THIRD_GEAR);return true;}@OnTransition(source = "THIRD_GEAR", target = "SECOND_GEAR")public boolean onDecelerateFromThirdGear(Message<CarEvent> message) {log.info("Decelerating from THIRD_GEAR to SECOND_GEAR");Car car = (Car) message.getHeaders().get("car");car.setCarState(CarState.SECOND_GEAR);return true;}@OnTransition(source = "SECOND_GEAR", target = "FIRST_GEAR")public boolean onDecelerateFromSecondGear(Message<CarEvent> message) {log.info("Decelerating from SECOND_GEAR to FIRST_GEAR");Car car = (Car) message.getHeaders().get("car");car.setCarState(CarState.FIRST_GEAR);return true;}@OnTransition(source = "FIRST_GEAR", target = "NEUTRAL")public boolean onDecelerateFromFirstGear(Message<CarEvent> message) {log.info("Decelerating from FIRST_GEAR to NEUTRAL");Car car = (Car) message.getHeaders().get("car");car.setCarState(CarState.NEUTRAL);return true;}}

4、使用状态机

@Service
public class CarService {@Resourceprivate StateMachine<CarState, CarEvent> carStateMachine;@Resourceprivate StateMachinePersister<CarState, CarEvent, Car> carMachinePersister;//模拟一个存储private Car car = new Car();//加速方法public Car acc() {if (car.getCarState() == null){car.setCarState(CarState.NEUTRAL);}// 书写逻辑Message message = MessageBuilder.withPayload(CarEvent.ACCELERATE).setHeader("car", car).build();if(changeStateAction(message,car)) {return car;}return car;}//减速方法public Car dece() {if (car.getCarState() == null){car.setCarState(CarState.NEUTRAL);}// 书写逻辑Message message = MessageBuilder.withPayload(CarEvent.DECELERATE).setHeader("car", car).build();if(changeStateAction(message,car)) {return car;}return car;}private boolean changeStateAction(Message<CarEvent> message, Car car) {try {carStateMachine.start();//尝试恢复状态机状态carMachinePersister.restore(carStateMachine, car); // 待议boolean res = carStateMachine.sendEvent(message);//持久化状态机状态carMachinePersister.persist(carStateMachine, car); // 持久return res;} catch (Exception e) {e.printStackTrace();} finally {carStateMachine.stop();}return false;}
}

4、场景(开车)

@SpringBootApplication
public class CarApplication {public static void main(String[] args) {ConfigurableApplicationContext context = SpringApplication.run(DesignApplication.class, args);CarService carService = context.getBean(CarService.class);Car car;car = carService.acc(); // 初始状态为空挡,加速后切换到1挡System.out.println("After accelerate: " + car.getCarState());car = carService.acc(); // 当前状态为1挡,加速后切换到2挡System.out.println("After accelerate: " + car.getCarState());car = carService.dece(); // 当前状态为2挡,减速后切换到1挡System.out.println("After decelerate: " + car.getCarState());car = carService.dece(); // 当前状态为1挡,减速后切换到空挡System.out.println("After decelerate: " + car.getCarState());}
}//输出
After accelerate: FIRST_GEAR
After accelerate: SECOND_GEAR
After decelerate: FIRST_GEAR
After decelerate: NEUTRAL

http://www.ppmy.cn/ops/152709.html

相关文章

两份PDF文档,如何比对差异,快速定位不同之处?

PDF文档比对是通过专门的工具或软件&#xff0c;自动检测两个PDF文件之间的差异&#xff0c;并以可视化的方式展示出来。这些差异可能包括文本内容的修改、图像的变化、表格数据的调整、格式的改变等。比对工具通常会标记出新增、删除或修改的部分&#xff0c;帮助用户快速定位…

字节启动AGI长期研究计划,代号Seed Edge

1月23日&#xff0c;据媒体报道&#xff0c;字节豆包大模型团队已在内部组建AGI长期研究团队&#xff0c;代号“Seed Edge”&#xff0c;鼓励项目成员探索更长周期、具有不确定性和大胆的AGI研究课题。接近字节的知情人士透露&#xff0c;Seed Edge的目标是探索AGI的新方法&…

leetcode_链表 21.合并两个有序链表

21.合并两个有序链表 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。思路&#xff1a; 定义一个哑节点&#xff08;dummy node&#xff09;&#xff0c;哑节点是一个初始的虚拟节点&#xff0c;它不存储有效值&#xff0c;只…

Flutter:搜索页,搜索bar封装

view 使用内置的Chip简化布局 import package:chenyanzhenxuan/common/index.dart; import package:ducafe_ui_core/ducafe_ui_core.dart; import package:flutter/material.dart; import package:get/get.dart; import package:tdesign_flutter/tdesign_flutter.dart;import i…

vscode下poetry管理项目的debug配置

点击debug选项的设置按钮&#xff0c;vscode会让我们编辑launch.json文件 {"version": "0.2.0","configurations": [{"name": "Python 调试程序: 当前文件","type": "debugpy","request": &…

数据库索引(1)

数据库索引 1.索引介绍 索引是一种 特殊的数据库结果&#xff0c;由数据表中的一列或多列组合而成&#xff0c;可以用来快速查询数据表中某一些特定值的记录。 通过索引&#xff0c;查询数据是不用读完记录的所有信息&#xff0c;而只是查询索引列。否则&#xff0c;数据库系…

什么是软件架构

什么是软件架构 程序员说&#xff0c;软件架构是要决定编写哪些C程序或OO类、使用哪些库和框架 程序经理说&#xff0c;软件架构就是模块的划分和接口的定义 系统分析员说&#xff0c;软件架构就是为业务领域对象的关系建模 配置管理员说&#xff0c;软件架构就是开发出来的…

【JVM】垃圾收集器详解

你将学到 1. Serial 收集器 2. ParNew 收集器 3. Parallel Scavenge 收集器 4. Serial Old 收集器 5. Parallel Old 收集器 6. CMS 收集器 7. G1 收集器 在 Java 中&#xff0c;垃圾回收&#xff08;GC&#xff09;是自动管理内存的一个重要机制。HotSpot JVM 提供了多种…