状态模式

本文最后更新于 2025年7月26日 晚上

当一个对象的内在状态改变时,允许改变其行为,这个对象看起来好像是改变了基类。

角色

  1. 含有状态的对象 : 它可以处理一些请求,这些请求最终产生的响应会与状态有关
  2. 状态接口 : 定义了每一个状态的行为集合,这些行为会在Context中得以使用
  3. 具体状态实现类 :实现相关行为的具体状态类

适用场景

用于减少判断逻辑,以及组织各种状况下的状态变更和跳转

实现状态模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// 定义抽象状态类
public abstract class LiftState{
protected Lift lift ;

public void setLift(Lift lift){
this.lift = lift ;
}

public abstract void open();

public abstract void close();

public abstract void run();

public abstract void stop();
}

// 定义状态实现类
public class OpeningLiftState extends LiftState{
@Override
public void open(){
System.out.println("open");
}
@Override
public void close(){
super.lift.setCurrentState(Lift.CLOSING_STATE);
super.lift.getCurrentState().close();
}
@Override
public void run(){
//
}
@Override
public void stop(){
//
}
}

public class ClosingLiftState extends LiftState{
@Override
public void open(){
super.lift.setCurrentState(Lift.OPENING_STATE);
super.lift.getCurrentState().open();
}
@Override
public void close(){
System.out.println("close");
}
@Override
public void run(){
super.lift.setCurrentState(Lift.RUNNING_STATE);
}
@Override
public void stop(){
super.lift.setCurrentState(Lift.STOPPING_STATE);
super.lift.getCurrentState().stop();
}
}

// 实际使用状态的类定义
public class Lift{
public final static LiftState OPENING_STATE = new OpeningLiftState();
public final static LiftState CLOSING_STATE = new ClosingLiftState();
public final static LiftState RUNNING_STATE = new RunningLiftState();
public final static LiftState STOPPING_STATE = new StoppingLiftState();

private LiftState currentState = CLOSING_STATE ;
public LiftState getCurrentState(){
return currentState;
}

public void setCurrentState(LiftState currentState){
this.currentState = currentState ;
this.currentState.setLift(this);
}

public void open(){
this.currentState.open();
}

public void close(){
this.currentState.close();
}

public void run(){
this.currentState.run();
}
public void stop(){
this.currentState.stop();
}
}

//调用
public class Test{
public static void main(String[] args){
Lift lift = new Lift();
lift.open()
// 此时调用的 是CLOSING_STATE 的open方法 将状态切换为OPENING_STATE
// 调用OPENING_STATE的open方法。

}
}

总结

状态模式是一种行为型设计模式,它通过将状态的行为封装到独立类中,实现了对象在不修改自身代码的前提下根据内部状态的不同而呈现出不同的行为。它的核心思想是: 将状态转移逻辑局部化,并将行为委托给当前状态对象 ,从而达到消除冗长条件判断、增强可读性和可扩展性的目的。在状态复杂、变化频繁的系统中,状态模式尤其适用,如电梯状态、工作流引擎、游戏角色状态机等场。


状态模式
http://gadoid.io/2025/07/26/状态模式/
作者
Codfish
发布于
2025年7月26日
许可协议